在使用AFNetworking 4进行文件上传时,可能会遇到上传进度不更新的问题,解决方法如下:
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"upload_url" parameters:nil constructingBodyWithBlock:^(id _Nonnull formData) {
[formData appendPartWithFileURL:fileURL
name:@"file"
fileName:fileName
mimeType:mimeType
error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
// 更新进度条
CGFloat progressValue = uploadProgress.fractionCompleted;
NSLog(@"上传进度: %f", progressValue);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
[uploadTask resume];
通过以上方法,可以解决AFNetworking 4上传进度不更新的问题。