Swift - Get file size from url

后端 未结 5 1018
终归单人心
终归单人心 2021-02-12 03:58

i am using documentPicker to get url path of any document and then uploaded to the database. I am choosing file (pdf, txt ..) , the upload is working but i want to limit the siz

5条回答
  •  感动是毒
    2021-02-12 04:44

    It's very easy with latest version of swift to calculate size of file using byte counter formatter:

    var fileSizeValue: UInt64 = 0

        do {
    
            let fileAttribute: [FileAttributeKey : Any] = try FileManager.default.attributesOfItem(atPath: url.path)
    
            if let fileNumberSize: NSNumber = fileAttribute[FileAttributeKey.size] as? NSNumber {
                fileSizeValue = UInt64(fileNumberSize)
    
                let byteCountFormatter: ByteCountFormatter = ByteCountFormatter()
                byteCountFormatter.countStyle = ByteCountFormatter.CountStyle.file
    
                byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useBytes
                print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue)))
    
                byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useKB
                print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue)))
    
                byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useMB
                print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue)))
    
            }
    
        } catch {
            print(error.localizedDescription)
        }
    

提交回复
热议问题