0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FileAttributeKeyを使ってファイルの情報を取得する

Last updated at Posted at 2023-10-03

概要

  • Swiftでファイルのサイズ・作成日時・inode番号などファイルの情報を取得したい。
  • これはFileManagerのattributesOfItem(atPath:)で情報が取得できる。
  • 具体的には下記のようにFinderの情報がいくつか取得することができる。
今回作成したもの Finder(参考)
image image

Gist

参考

実装

  • 下記は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を作成した
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
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?