概要
- Swiftでファイルのサイズ・作成日時・inode番号などファイルの情報を取得したい。
- これはFileManagerのattributesOfItem(atPath:)で情報が取得できる。
- 具体的には下記のようにFinderの情報がいくつか取得することができる。
今回作成したもの | Finder(参考) |
---|---|
![]() |
![]() |
Gist
参考
- [iOSアプリ開発] ファイルを抽象化した構造体を作る(5)
- AppleのドキュメントにはC言語のデータ型が載っているので、Swiftに変換する時の参考に
- FileAttributeKey
- Dateに関して
実装
- 下記はFileAttributeKeyのsizeを使用した例で、ファイルサイズを取得する例である。
let url = URL(fileURLWithPath: "/Users/ikeh/Downloads/InodeDemo/README.md")
guard let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
let size = attributes[.size] as? NSNumber else {
return
}
print(size) // 568bytes
- FileAttributeKeyには色々種類があり、例えば作成日時・更新日時・inode番号などが取得できる。
- 種類が多いので今回下記のように、情報を取得するためのstructを作成した
- ※一部の抜粋。他はFileAttributesManager.mdを参照ください。
struct FileAttributesManager {
// MARK: - Error Define
enum FileAttributesError: Error {
case typeCastingError
}
// MARK: - General
static private var fileManager: FileManager = .default
static private func loadAttributes(url: URL) throws -> [FileAttributeKey : Any] {
try fileManager.attributesOfItem(atPath: url.path)
}
}
// MARK: - Parameters
extension FileAttributesManager {
// ファイルの作成日時
// The key in a file attribute dictionary whose value indicates the file's creation date.
static func creationDate(url: URL) throws -> Date {
let attributes = try loadAttributes(url: url)
guard let creationDate = attributes[.creationDate] as? Date else {
throw FileAttributesError.typeCastingError
}
return creationDate
}
// ファイルサイズのバイト数
// The key in a file attribute dictionary whose value indicates the file’s size in bytes.
static func size(url: URL) throws -> UInt64 {
let attributes = try loadAttributes(url: url)
guard let size = attributes[.size] as? NSNumber else {
throw FileAttributesError.typeCastingError
}
return size.uint64Value
}
}
- 呼び出し例は以下の通り
guard let size = try? FileAttributesManager.size(url: url),
let creationDate = try? FileAttributesManager.creationDate(url: url),
let modificationDate = try? FileAttributesManager.modificationDate(url: url) else {
return nil
}