Swift - Get file size from url

后端 未结 5 1016
终归单人心
终归单人心 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 05:01

    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
        }
    

提交回复
热议问题