ios objective-c : How to get NSURLSession to return Content-Length(http header) from server

标签 ios objective-c nsurlsession nsurlsessiondownloadtask

我已经尝试过
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/

相关文章:

iOS:选择查询在某些设备上返回不同的结果

swift - 使用 URLSessionDownloadDelegate 获取 HTTP header

ios - ETag 和 If-None-Match HTTP header 不起作用

ios - 如何将删除附件添加到自定义单元格?

ios - 在为 iOS 模拟器构建时让 Xcode 忽略静态库

ios - iOS 中的 TouchBegan 和响应者

ios - 如何在类扩展中添加静态(存储)属性以创建单例? ( swift )

iphone - 指向外部对象的指针为零

ios - 缺少 View Controller

ios - 如何从 UITableViewCell 内的 URL 设置 UIImageView 的图像?