2016-12-02 36 views
2

返回的Content-Length(HTTP標頭)我已經嘗試過
How to get NSURLSession to return Content-Length(http header) from server. Objective-c, iosIOS目標C:如何獲得NSURLSession從服務器

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

回答

2

這是因爲你正在返回completion handler以外的函數值,所以你的函數在得到服務器的響應之前返回值。現在您無法從completion handler返回值。所以,你需要創建一個方法,它具有自定義completion handler作爲參數類似,

- (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]; 

} 

,你可以迅速的3.0調用此方法一樣,

[self getContentLength:^(long long returnValue) { 

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

}]; 
2

: (使用一個普通的,老式功能..)

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。