我想在下载之前从网址获取文件大小
这是obj-c代码
NSURL *URL = [NSURL URLWithString:"ExampleURL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error: nil];
long long size = [response expectedContentLength];
这里是Swift Code
var url:NSURL = NSURL(string: "ExmapleURL")
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "HEAD"
var response = NSHTTPURLResponse()
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)
但我在这里有错误
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)
'NSHTTPURLResponse' is not identical to 'NSURLResponse?'
我在这里错过了什么东西?
答案 0 :(得分:3)
响应参数的类型为
AutoreleasingUnsafeMutablePointer<NSURLResponse?>
这意味着您可以将可选 NSURLResponse
的地址作为参数传递:
var response : NSURLResponse?
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response , error: nil)
然后,您可以有条件地将返回的回复转换为NSHTTPURLResponse
:
if let httpResponse = response as? NSHTTPURLResponse {
println(httpResponse.expectedContentLength)
}
请注意,您应该检查sendSynchronousRequest()
的返回值
如果无法建立联系,则为nil
。
还建议拨打此电话
方法只来自一个单独的线程(或使用sendAsynchronousRequest()
代替)
因为建立连接可能需要一段时间
- 特别是在使用蜂窝网络时 - 主线程将是
否则阻止。
答案 1 :(得分:1)
Swift 4解决方案:
func fetchContentLength(for url: URL, completionHandler: @escaping (_ contentLength: Int64?) -> ()) {
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil, let response = response as? HTTPURLResponse, let contentLength = response.allHeaderFields["Content-Length"] as? String else {
completionHandler(nil)
return
}
completionHandler(Int64(contentLength))
}
task.resume()
}
// Usage:
let url = URL(string: "https://s3.amazonaws.com/x265.org/video/Tears_400_x265.mp4")!
fetchContentLength(for: url, completionHandler: { contentLength in
print(contentLength ?? 0)
})