我的应用程序有一个将图像上传到网络服务器的功能。虽然这是在后台发生的,但我设置了一个进度条,以便用户可以看到上传状态。我正在上传进度条,如下所示。只要没有发出其他 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 调用响应
成功:图片上传响应