iOS在下载前获取文件大小

Nic*_*ost 0 size download ios nsurlsession nsurlsessiondownloadtask

我找不到适合我的解决方案。但是我需要获取正在下载的视频的文件大小,以便确保用户的手机上有足够的空间来容纳它。

我的想法是检查视频的大小,然后如果用户有足够的空间来下载它。有什么建议吗?

NSURL *url = [NSURL URLWithString:stringURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {...}];
Run Code Online (Sandbox Code Playgroud)

Ala*_*man 7

这是其他答案的一种变体,它使用函数(在Swift 4中)在检索大小时调用闭包:

func getDownloadSize(url: URL, completion: @escaping (Int64, Error?) -> Void) {
    let timeoutInterval = 5.0
    var request = URLRequest(url: url,
                             cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
                             timeoutInterval: timeoutInterval)
    request.httpMethod = "HEAD"
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        let contentLength = response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
        completion(contentLength, error)
    }.resume()
}
Run Code Online (Sandbox Code Playgroud)

使用此功能的方法如下:

let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/7/70/Example.png")!
getDownloadSize(url: url, completion: { (size, error) in
    if error != nil {
        print("An error occurred when retrieving the download size: \(error.localizedDescription)")
    } else {
        print("The download size is \(size).")
    }
})
Run Code Online (Sandbox Code Playgroud)