我已经尝试过
How to get NSURLSession to return Content-Length(http header) from server. Objective-c, ios
- (long long) getContentLength
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
request.HTTPMethod = @"HEAD";
[request addValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
NSURLSessionDownloadTask *uploadTask
= [session downloadTaskWithRequest:request
completionHandler:^(NSURL *url,NSURLResponse *response,NSError *error) {
NSLog(@"handler size: %lld", response.expectedContentLength);
totalContentFileLength = [[NSNumber alloc] initWithFloat:response.expectedContentLength].longLongValue;
}];
NSLog(@"content length=%lld", totalContentFileLength);
[uploadTask resume];
return totalContentFileLength;
}
我从返回值中得到的总是0
。
最佳答案
对于 Swift 3.0: (使用简单的旧式函数..)
func getContentLengthOf(urlString: String,
completionHandler: @escaping (Int64?) -> () ) {
let url = URL(string: urlString)
var request = URLRequest(url: url!)
request.httpMethod = "HEAD"
request.addValue( "identity", forHTTPHeaderField: "Accept-Encoding")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode {
let contentLength : Int64 = response.expectedContentLength
completionHandler(contentLength)
} else {
completionHandler(nil)
}
})
task.resume()
}
并这样调用:
....
let URLString = "https://lh4.googleusercontent.com/-KdgJnz1HIdQ/AAAAAAAAAAI/AAAAAAAAA8s/31PBnNCL-qs/s0-c-k-no-ns/photo.jpg"
getContentLengthOf(urlString: URLString) { (contentLength: Int64?) in
if let contentLength = contentLength {
print("size is: \(contentLength)")
}else{
print("error getting contentLength")
}
}
在回调中,您将获得一个可选的 Int64。
关于ios objective-c : How to get NSURLSession to return Content-Length(http header) from server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40926383/