NSURLConnection,didReceiveResponse expectedContentLength得-1

时间:2017-03-21 07:43:56

标签: ios objective-c nsurlconnection nsurlrequest

我正在使用GET从服务器获取数据,想要实现进度条,因为我试图在didReceiveResponse委托方法中捕获expectedContentLength。 怎么能解决?

NSString* serverUrl = @"https:testURL";

receivedData = [[NSMutableData alloc] initWithLength:0];

NSURL* url =[NSURL URLWithString:[serverUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

[theRequest setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];**(I tried it after seeing other solutions over Web)**

[NSURLConnection connectionWithRequest:theRequest delegate:self];

...

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    [receivedData setLength:0];
    expectedBytes = [response expectedContentLength];
}

1 个答案:

答案 0 :(得分:0)

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
     _contentLength = [response expectedContentLength];

}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
 _receiveLength += data.length;
}

你这么认为吗?