ios目标c:如何让NSURLSession从服务器返回内容长度(http头)

ios目标c:如何让NSURLSession从服务器返回内容长度(http头),ios,objective-c,nsurlsession,nsurlsessiondownloadtask,Ios,Objective C,Nsurlsession,Nsurlsessiondownloadtask,我已经试过了 我总是从返回值中得到0。这是因为您在完成处理程序之外返回函数的值,所以您的函数在从服务器得到响应之前返回值。现在您无法从完成处理程序返回值。因此,您需要创建一个方法,该方法将自定义的完成处理程序作为参数,例如 - (void) getContentLength : (void(^)(long long returnValue))completionHandler { NSURLSessionConfiguration *config = [NSURLSessionConf

我已经试过了


我总是从返回值中得到
0

这是因为您在
完成处理程序之外返回函数的值,所以您的函数在从服务器得到响应之前返回值。现在您无法从
完成处理程序返回值。因此,您需要创建一个方法,该方法将自定义的
完成处理程序
作为参数,例如

 - (void) getContentLength : (void(^)(long long returnValue))completionHandler
 {


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;

                     completionHandler(totalContentFileLength);

                 }];
NSLog(@"content length=%lld", totalContentFileLength);
[uploadTask resume];

}
你可以这样调用这个方法

   [self getContentLength:^(long long returnValue) {

    NSLog(@"your content length : %lld",returnValue);

}];
对于swift 3.0: (使用普通的老式函数..)

这样称呼:

....
        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

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")
            }
        }