How to find size of a file before downloading it in iOS 7?

前端 未结 7 1687
天涯浪人
天涯浪人 2020-12-02 00:43

Wanted to find size of a file on some server before downloading it in iOS 7... I have a method of NSURLConnectionDelegate but it is deprecated after iOS 4.3

Here was

相关标签:
7条回答
  • 2020-12-02 01:23

    Also using URlSession you can get the file size like this without downloading actual data:

    func getPdfSize(for url: URL) {
        var request = URLRequest(url: url)
        request.httpMethod = "HEAD"
    
        URLSession.shared.dataTask(with: request) { [weak self] (_, response, _) in
            if let response = response {
                let size = response.expectedContentLength
                DispatchQueue.main.async {
                    self?.fileSizeLabel.text = ByteCountFormatter.string(fromByteCount: size, countStyle: .file)
                }
            }
        }.resume()
    }
    

    Notice also you can use the native iOS ByteCountFormatter to format the byte count into a readable string.

    Code in Swift 5

    0 讨论(0)
提交回复
热议问题