Finding file's size

雨燕双飞 提交于 2019-11-27 11:25:39

Try this;

NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];

NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];

Note that the fileSize won't necessarily fit in an integer (especially a signed one) although you could certainly drop to a long for iOS as you'll never exceed that in reality. The example uses long long as in my code I have to be compatible with systems with much larger storage available.

One liner in Swift:

let fileSize = try! NSFileManager.defaultManager().attributesOfItemAtPath(fileURL.path!)[NSFileSize]!.longLongValue

If you have a URL (NSURL, not a String), you can get the file size without a FileManager:

 let attributes = try? myURL.resourceValues(forKeys: Set([.fileSizeKey]))
 let fileSize = attributes?.fileSize // Int?

Swift 4.x

do {
    let fileSize = try (FileManager.default.attributesOfItem(atPath: filePath) as NSDictionary).fileSize()
            print(fileSize)
    } catch let error {
            print(error)
    }

Get the file size in MB Try This code for swift

func getSizeOfFile(withPath path:String) -> UInt64?
{
    var totalSpace : UInt64?

    var dict : [FileAttributeKey : Any]?

    do {
        dict = try FileManager.default.attributesOfItem(atPath: path)
    } catch let error as NSError {
         print(error.localizedDescription)
    }

    if dict != nil {
        let fileSystemSizeInBytes = dict![FileAttributeKey.systemSize] as! NSNumber

        totalSpace = fileSystemSizeInBytes.uint64Value
        return (totalSpace!/1024)/1024
    }
    return nil
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!