uploadTaskWithStreamedRequest中的AFNetworking错误 [英] AFNetworking error in uploadTaskWithStreamedRequest
问题描述
错误
Terminating app due to uncaught exception 'NSGenericException', reason: 'Upload tasks in background sessions must be from a file'
当我尝试
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
配置
为 NSURLSession
工作正常,但是当我使用波纹管配置
时,应用程序崩溃并给我错误。
configuration
for NSURLSession
work fine but when i use bellow configuration
then application crash and give me error.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:kBackgroundSessionIdentifier];
推荐答案
您应使用 uploadTaskWithRequest: fromFile:
。这里的问题是,您必须将分段请求的内容写入临时文件,然后上传该文件。
You should use uploadTaskWithRequest:fromFile:
only. The catch here is that you have to write your multipart request contents to a temp file and then upload that file.
您应使用 AFHTTPRequestSerializer:requestWithMultipartFormRequest :writingStreamContentsToFile:completionHandler:
。
请参见 https://github.com/AFNetworking/AFNetworking/issues/1874-兰辛的答案
You should use AFHTTPRequestSerializer:requestWithMultipartFormRequest:writingStreamContentsToFile:completionHandler:
.
Refer https://github.com/AFNetworking/AFNetworking/issues/1874 - Lansing's answer
以下是对我有用的示例代码:
Here is the sample code that worked for me:
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:TEMP_DATA_FILE];
[data writeToFile:filePath atomically:YES];
NSURL *filepathURL = [NSURL fileURLWithPath:filePath];
NSString *tempFile = [NSTemporaryDirectory() stringByAppendingPathComponent:TEMP_MULTI_PART_REQUEST_FILE];
NSURL *filePathtemp = [NSURL fileURLWithPath:tempFile];
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSError *error = nil;
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:@"POST" URLString:AppendStrings(HOST_FOR_SERVICE_ACCESS, SERVICE_FOR_MULTIPART_UPLOAD)
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{[formData appendPartWithFileURL:filepathURL name:@"data" error:nil];}
error:&error ];
__block NSProgress *progress = nil;
[serializer requestWithMultipartFormRequest:request writingStreamContentsToFile:filePathtemp completionHandler:^(NSError *error) {
NSURLSessionUploadTask *uploadTask = [self.sessionManager uploadTaskWithRequest:request fromFile:filePathtemp progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {}];
[uploadTask resume];
记住以后要清理临时文件。
Remember to clean up your temp files afterwards.
这篇关于uploadTaskWithStreamedRequest中的AFNetworking错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!