我是較新的 AFNetworking 2.0。使用下面的代碼片斷,我已經可以成功地將一張照片上傳到個人 url。我想要跟蹤的增量上載進度,但我找不到這樣作 2.0 版的示例。個人應用程序是 iOS 7,因此我已經選擇了爲 AFHTTPSessionManager。app
任何人均可以提供如何修改這段上傳進度進行跟蹤的示例?url
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
不能提供一種方法來設置進度塊。相反,必須進行如下操做:code
// 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:]
,從您捆綁直接讀取該文件。orm