【Swift】FileのサイズをFileManagerで取得する方法!MBで表示

この記事からわかること

  • SwiftFileManagerの使い方
  • ローカル保存したファイルサイズ容量取得するには?
  • attributesOfItemメソッドとは?
  • 取得できるファイル属性種類
  • MB変換する方法

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

環境

ローカルに保存しているファイルのサイズを取得する方法

FileManagerクラスやCore Dataなどを使用してローカルに保存しているファイルのサイズ(容量)を取得するにはFileManagerクラスのattributesOfItemメソッドを使用します。

let manager = FileManager.default
guard let docURL = manager.urls(for: .documentDirectory, in: .userDomainMask).first else {
    fatalError("URL取得失敗")
}
// ファイル名を含めたフルパスを生成
let fullURL = docURL.appendingPathComponent("sample.txt")

do {
    // 書き込み処理
    try "Hello World!".write(to: fullURL,atomically: true,encoding: .utf8)
} catch{
    print("書き込み失敗")
}

let attributes = try? manager.attributesOfItem(atPath: fullURL.path) as NSDictionary
print(attributes?.fileSize()) // Optional(14)

attributesOfItemメソッド

attributesOfItemは引数に対象のファイルのパスを渡し、返り値は[FileAttributeKey : Any]型になります。

func attributesOfItem(atPath path: String) throws -> [FileAttributeKey : Any]

NSDictionary型にキャストするとfileSizefileModificationDateメソッドが使用できるようになります。

let attributes = try? manager.attributesOfItem(atPath: fullURL.path) as NSDictionary
print(attributes?.fileSize())

NSDictionary型にキャストしない場合はFileAttributeKey型でキー値を指定することも可能です。

let attributes = try? manager.attributesOfItem(atPath: fullURL.path)
print(attributes?[.size])

取得できるファイル属性

容量だけでなく作成日や更新日など様々な情報を取得することが可能です。以下は実際に取得した中身です。

Optional({
    NSFileCreationDate = "2023-11-29 09:58:30 +0000";
    NSFileExtendedAttributes =     {
        "com.apple.TextEncoding" = {length = 15, bytes = 0x7574662d383b313334323137393834};
    };
    NSFileExtensionHidden = 0;
    NSFileGroupOwnerAccountID = 20;
    NSFileGroupOwnerAccountName = staff;
    NSFileModificationDate = "2023-11-29 09:58:30 +0000";
    NSFileOwnerAccountID = 501;
    NSFilePosixPermissions = 420;
    NSFileReferenceCount = 1;
    NSFileSize = 14;
    NSFileSystemFileNumber = 81390572;
    NSFileSystemNumber = 16777234;
    NSFileType = NSFileTypeRegular;
})

MBに変換する

ファイルサイズはバイト単位で取得できるのでそのまま使用するには分かりにくいです。MB単位に変換して数値で取得したい場合は1024 * 1024で割って取得することが可能です。

let size = attributes?[.size]

if let bytes = size as? Int64 {
    print(bytes) // 423360
    let sizeInMB = Double(bytes) / (1024 * 1024)
    print(sizeInMB) // 0.40374755859375
}

文字列でMBで取得するにはByteCountFormatterを使用してuseMBを指定することで0.4 MB形式で取得することができます。useMBを変更すればuseKBなどに変更することで任意の単位で簡単に取得することが可能です。

let size = attributes?[.size]
            
if let bytes = size as? Int64 {
    let bcf = ByteCountFormatter()
    bcf.allowedUnits = [.useMB]
    bcf.countStyle = .file
    print(bcf.string(fromByteCount: bytes)) // 0.4 MB
}

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。

ご覧いただきありがとうございました。

searchbox

スポンサー

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑
今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index