所以在我的应用程序中,我使用NSURLConnection连接到服务器并检索文本。这就是我启动NSURLConnection的方式:
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:postUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
//Some other code
[serviceRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
[serviceRequest setHTTPMethod:@"POST"];
[serviceRequest setHTTPBody:postData];
//Force to return size
[serviceRequest setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];
theConnection = [[NSURLConnection alloc] initWithRequest:serviceRequest delegate:self];
现在它工作正常,但我想在我的应用程序中获得一个进度条来表示此请求的进度。
现在这里是我的didReceiveResponse和didReceiveData方法:
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
dlSize = [response expectedContentLength];
NSLog(@"didReceiveResponse: %f", dlSize);
[self.receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
dlProgress = ((float) [data length] / (float) dlSize);
NSLog(@"dlProgress: %f", dlProgress);
}
所以这就是问题所在。正如你所看到的那样,我有两个NSLog,但是在请求完成之前它们不会被调用。具体来说,我正在联系服务器给OCR一些事情,一旦完成OCRing,我得到了文本,即调用这两种方法的时候。然后日志返回如下内容:
2013-07-30 22:50:09.201 app[39381:907] didReceiveResponse: 514.000000
2013-07-30 22:50:09.202 app[39381:907] dlProgress: 1.000000
2013-07-30 22:54:39.651 app[39381:907] didReceiveResponse: 305.000000
2013-07-30 22:54:39.651 app[39381:907] dlProgress: 1.000000
我不确定为什么在请求期间没有调用这些方法,但是这个网站上有人知道为什么?无论如何任何提示/意见/建议都很受欢迎,所以我可以得到一个与此相关的UIProgressView。
谢谢!
答案 0 :(得分:1)
在yourViewController.h中声明NSURLResponse *响应; 在这个方法中只写:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse
{
response = aResponse;
}
之后(downData是一个NSMUtableData)(progresso是UIProgressView):
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[downData appendData:data];
float expectedLength = [response expectedContentLength];
float currentLength = downData.length;
progresso.progress = currentLength / expectedLength;
if (currentLength/expectedLength == 1) {
//do anything
}
}