0

Error

Terminating app due to uncaught exception 'NSGenericException', reason: 'Upload tasks in background sessions must be from a file'

when i try

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

configuration for NSURLSession work fine but when i use bellow configuration then application crash and give me error.

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:kBackgroundSessionIdentifier];
Lalji
  • 695
  • 1
  • 6
  • 19

2 Answers2

3

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.

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.

iphonic
  • 12,050
  • 4
  • 50
  • 94
tuttu47
  • 481
  • 1
  • 4
  • 19
0

The Exception which says "Upload tasks in background sessions must be from a file" itself is the answer to this question.

The following line creates a background session configuration.

[NSURLSessionConfiguration backgroundSessionConfiguration:kBackgroundSessionIdentifier];

which wont support uploadTaskWithStreamedRequest: but works with uploadTaskWithRequest:request fromFile:

From Apple documentation background uploads work only with Files. If you want to upload in background, write your data to file, then pass a url to that tile to you background session

Xcoder
  • 1,747
  • 13
  • 17