ios AFNetworking 2.0 跟踪文件上传进度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20533890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:44:19  来源:igfitidea点击:

AFNetworking 2.0 track file upload progress

iosafnetworking-2

提问by Benchtop Creative

I am relatively new to AFNetworking 2.0. Using the code snippet below, I've been able to successfully upload a photo to my url. I would like to track the incremental upload progress, but I cannot find an example of doing this with version 2.0. My application is iOS 7, so I've opted for AFHTTPSessionManager.

我对 AFNetworking 2.0 比较陌生。使用下面的代码片段,我已经能够成功地将照片上传到我的网址。我想跟踪增量上传进度,但找不到使用 2.0 版执行此操作的示例。我的应用程序是 iOS 7,所以我选择了 AFHTTPSessionManager。

Can anyone offer an example of how to modify this snippet to track upload progress?

谁能提供一个如何修改此代码段以跟踪上传进度的示例?

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"myimage.jpg"], 1.0);

[manager POST:@"http://myurl.com" parameters:dataToPost constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"attachment" fileName:@"myimage.jpg" mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"Success %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Failure %@, %@", error, [task.response description]);
}];

回答by StatusReport

The interface of AFHTTPSessiondoesn't provide a method to set a progress block. Instead, you'll have to do the following:

的接口AFHTTPSession没有提供设置进度块的方法。相反,您必须执行以下操作:

// 1. Create `AFHTTPRequestSerializer` which will create your request.
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];

// 2. Create an `NSMutableURLRequest`.
NSMutableURLRequest *request =
    [serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://www.myurl.com"
                                    parameters:dataToPost
                     constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                       [formData appendPartWithFileData:imageData
                                                   name:@"attachment"
                                               fileName:@"myimage.jpg"
                                               mimeType:@"image/jpeg"];
                     }];

// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation =
    [manager HTTPRequestOperationWithRequest:request
                                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                       NSLog(@"Success %@", responseObject);
                                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                       NSLog(@"Failure %@", error.description);
                                     }];

// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                    long long totalBytesWritten,
                                    long long totalBytesExpectedToWrite) {
  NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
}];

// 5. Begin!
[operation start];

In addition, you don't have to read the image via UIImageand then compress it again using JPEG to get an NSData. Just use +[NSData dataWithContentsOfFile:]to read the file directly from your bundle.

此外,您不必通过读取图像UIImage然后使用 JPEG 再次压缩它以获得NSData. 只需用于+[NSData dataWithContentsOfFile:]直接从您的包中读取文件。

回答by dopcn

It's true the interface of AFHTTPSessionManagerdoesn't provide a method to track the upload progress. Butthe AFURLSessionManagerdoes.

确实, 的接口AFHTTPSessionManager没有提供跟踪上传进度的方法。AFURLSessionManager做。

As a inherited class of AFURLSessionManagerAFHTTPSessionManagercan track upload progress like this:

作为AFURLSessionManagerAFHTTPSessionManager可以跟踪上传进度的继承类,如下所示:

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]  multipartFormRequestWithMethod:@"POST" URLString:kUploadImageURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5) name:@"uploadFile" fileName:@"image" mimeType:@"image/jpeg"];
} error:nil];

NSProgress *progress;
NSURLSessionDataTask *uploadTask = [[AFHTTPSessionManager sharedManager] uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (!error) {
        //handle upload success
    } else {
        //handle upload failure
    }
}];
[uploadTask resume];
[progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];

outside

外部

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
        NSProgress *progress = (NSProgress *)object;
        //progress.fractionCompleted tells you the percent in CGFloat
    }
}

Here is method 2(updated)

这是方法2(更新)

use KVOto track progress means selfneed to be alive during observation. The more elegant way is AFURLSessionManager's method setTaskDidSendBodyDataBlock, like this:

用于KVO跟踪进度意味着self在观察期间需要活着。更优雅的方法是AFURLSessionManager's method setTaskDidSendBodyDataBlock,如下所示:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setTaskDidSendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
    //during the progress
}];

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]  multipartFormRequestWithMethod:@"POST" URLString:kUploadImageURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5) name:@"uploadFile" fileName:@"image" mimeType:@"image/jpeg"];
} error:nil];

NSURLSessionDataTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (!error) {
        //handle upload success
    } else {
        //handle upload failure
    }
}];
[uploadTask resume];