我的应用程序有一个功能可以将图像上传到Web服务器。虽然这在后台发生,但我设置了一个进度条,以便用户可以看到上传状态。我正在上传进度条,如下所示。只要没有其他HTTP请求,一切正常。一旦另一个请求被设置,setUploadProgressBlock就会停止更新,但最终会调用setCompletionBlockWithSuccess,所以我的进度条将在30到70之间的某个百分比,但上传实际上已经完成。对于其他请求,我没有使用AFNetworking。下面还有一个例子。我试过调用[operation waitUntillFinished]和我在网上看过的其他几个例子,但似乎没有任何工作。
图片上传=
NSData *postData= [[NSString stringWithFormat:@"description=%@&location=%@&image=%@",i, l, d] dataUsingEncoding:NSNonLossyASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"%@/upload/create", SERVICE_URL]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:postData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
float percentDone = ((float)(totalBytesWritten) / (float)(totalBytesExpectedToWrite));
[progressLabel setText:[NSString stringWithFormat:@"%.0f%%", (percentDone * 100)]];
[progressView setProgress:percentDone];
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"success: %@", operation.responseString);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
}
];
[httpClient enqueueHTTPRequestOperation:operation];
所有其他请求=
NSURL *loginURL = [NSURL URLWithString: [NSString stringWithFormat:@"%@/user/add", SERVICE_URL]];
NSData *postData= [[NSString stringWithFormat:@"user_id=%@", user_id] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:loginURL];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:postData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:theRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
}];
更新
为了解释一下,这里有一个控制台在这个过程中会是什么样子的例子 -
发送437568个769069字节
发送了另一个API调用
进度条停止更新
另一个API调用响应
成功:图片上传回复
答案 0 :(得分:1)
您的无主HTTP客户端实例可能在操作完成之前被释放。使用示例中显示的静态单例模式,或将其存储在某个拥有的视图控制器的strong
属性中。
答案 1 :(得分:0)
setText:
和setProgress
是从错误的线程调用的,未获得更新是这里可能发生的危害最小的事情。
使用
dispatch_async(dispatch_get_main_queue(), ^ {
[progressLabel setText:[NSString stringWithFormat:@"%.0f%%", (percentDone * 100)]];
[progressView setProgress:percentDone];
});
或
[progressLabel performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:@"%.0f%%", (percentDone * 100)] waitUntilDone:NO];
[progressView performSelectorOnMainThread:@selector(setProgress:) withObject:(id)percentDone waitUntilDone:NO];
答案 2 :(得分:0)
切换到ASIHTTPRequest(http://allseeing-i.com/ASIHTTPRequest/)以检索上传进度并解决问题!