Swift - Get file size from url

六眼飞鱼酱① 提交于 2019-12-04 16:59:53

问题


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 size of the file .

 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {

        self.file = url //url
        self.path = String(describing: self.file!) // url to string
        self.upload = true //set upload to true
        self.attachBtn.setImage(UIImage(named: "attachFilled"), for: .normal)//set image
        self.attachBtn.tintColor = UIColor.black //set color tint
        sendbtn.tintColor = UIColor.white //


        do
        {
            let fileDictionary = try FileManager.default.attributesOfItem(atPath: self.path!)
            let fileSize = fileDictionary[FileAttributeKey.size]
            print ("\(fileSize)")
        } 
        catch{
            print("Error: \(error)")
        }

    }

I get the error message , this file does not exist , where does the document picker save the file and how to get his attributes.


回答1:


First of all, in the file system you get the path of a URL with the path property.

self.path = url.path

But you don't need that at all. You can retrieve the file size from the URL directly:

self.path = String(describing: self.file!) // url to string

do {
    let resources = try url.resourceValues(forKeys:[.fileSizeKey])
    let fileSize = resources.fileSize!
    print ("\(fileSize)")
} catch {
    print("Error: \(error)")
}



回答2:


Swift 4:

func sizePerMB(url: URL?) -> Double {
    guard let filePath = url?.path else {
        return 0.0
    }
    do {
        let attribute = try FileManager.default.attributesOfItem(atPath: filePath)
        if let size = attribute[FileAttributeKey.size] as? NSNumber {
            return size.doubleValue / 1000000.0
        }
    } catch {
        print("Error: \(error)")
    }
    return 0.0
}



回答3:


Swift 4.1 & 5

func fileSize(forURL url: Any) -> Double {
        var fileURL: URL?
        var fileSize: Double = 0.0
        if (url is URL) || (url is String)
        {
            if (url is URL) {
                fileURL = url as? URL
            }
            else {
                fileURL = URL(fileURLWithPath: url as! String)
            }
            var fileSizeValue = 0.0
            try? fileSizeValue = (fileURL?.resourceValues(forKeys: [URLResourceKey.fileSizeKey]).allValues.first?.value as! Double?)!
            if fileSizeValue > 0.0 {
                fileSize = (Double(fileSizeValue) / (1024 * 1024))
            }
        }
        return fileSize
    }



回答4:


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)
    }


来源:https://stackoverflow.com/questions/43797281/swift-get-file-size-from-url

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