gpt4 book ai didi

ios - AFNetworking 2.0 跟踪文件上传进度

转载 作者:IT王子 更新时间:2023-10-29 07:52:24 26 4
gpt4 key购买 nike

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

谁能举例说明如何修改此代码段以跟踪上传进度?

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]);
}];

最佳答案

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

// 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];

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

关于ios - AFNetworking 2.0 跟踪文件上传进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20533890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com