LoginSignup
25
23

More than 5 years have passed since last update.

Swiftでファイル/ディレクトリの更新日付やサイズを取得するには

Last updated at Posted at 2015-01-06

結論

これで良さそう。

let path = "..."         
if let attr: NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(path, error: nil) {
     println(attr.fileModificationDate())
     println(attr.fileSize())
}

事の経緯

関数の定義を見ると

Swift
func attributesOfItemAtPath(path: String, error: NSErrorPointer) -> [NSObject : AnyObject]?

というように、戻り値の型が[NSObject: AnyObject]?になっているのですが、この辞書型から更新日付などを"お手軽に"取り出す方法が当初解りませんでした。

Objective-Cでは、NSDirectory型で結果が得られ、カテゴリで各情報が取り出しやすいようになっていましたが、

Objective-C

- (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

@interface NSDictionary (NSFileAttributes)

- (unsigned long long)fileSize;
- (NSDate *)fileModificationDate;
- (NSString *)fileType;
- (NSUInteger)filePosixPermissions;
- (NSString *)fileOwnerAccountName;
- (NSString *)fileGroupOwnerAccountName;
- (NSInteger)fileSystemNumber;
- (NSUInteger)fileSystemFileNumber;
- (BOOL)fileExtensionHidden;
- (OSType)fileHFSCreatorCode;
- (OSType)fileHFSTypeCode;
- (BOOL)fileIsImmutable;
- (BOOL)fileIsAppendOnly;
- (NSDate *)fileCreationDate;
- (NSNumber *)fileOwnerAccountID;
- (NSNumber *)fileGroupOwnerAccountID;
@end

Swiftだとどうなるんだろう?と思い、調べていくうちにそれらしい補助関数を発見。

Swift
extension NSDictionary {

    func fileSize() -> UInt64
    func fileModificationDate() -> NSDate?
    func fileType() -> String?
    func filePosixPermissions() -> Int
    func fileOwnerAccountName() -> String?
    func fileGroupOwnerAccountName() -> String?
    func fileSystemNumber() -> Int
    func fileSystemFileNumber() -> Int
    func fileExtensionHidden() -> Bool
    func fileHFSCreatorCode() -> OSType
    func fileHFSTypeCode() -> OSType
    func fileIsImmutable() -> Bool
    func fileIsAppendOnly() -> Bool
    func fileCreationDate() -> NSDate?
    func fileOwnerAccountID() -> NSNumber?
    func fileGroupOwnerAccountID() -> NSNumber?
}

[NSObject: AnyObject]?型からNSDictionary型に変換すれば行けそう!ってな所まで来ましたが、どうやって変換すればいいのか判らず...

どうやら、普通にasや型指定だけで[NSObject: AnyObject]型からNSDictionary型へは変換(ブリッジ)できるもよう。

この辺は公式ドキュメントにも載っていました(Dictionaries項目参照)。
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

試したソースも載せておきます。

Swift
import UIKit

let dic: [NSObject: AnyObject] = ["aaa": "bbb"]
let test1 = dic as NSDictionary // OK
let test2: NSDictionary = dic // OK

ということで、if letでアンラップしつつNSDictionary型にするという冒頭のコードになりました。

25
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
23