How to upload task in background using afnetworking

a 夏天 提交于 2019-12-03 12:31:46

I'm answering my own question in hopes that it will help a few people.

I can't find this documented anywhere, but it looks like you have to use uploadTaskWithRequest:fromFile:progress:completionHandler: when using a background session configuration.

Here is a simple example:

AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];

id config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.opentext.core.uploadservice"];
id session = [NSURLSession sessionWithConfiguration:config delegate:appDelegate delegateQueue:[NSOperationQueue new]];

OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
//[multipartFormData addFile:data parameterName:@"file" filename:nil contentType:nil];
[multipartFormData addParameters:[uploadBundle getParameters]];

NSURLRequest *rq = [OMGHTTPURLRQ POST:[uploadBundle.uploadUrl absoluteString] :multipartFormData];

id path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"upload.NSData"];
[rq.HTTPBody writeToFile:path atomically:YES];

[[session uploadTaskWithRequest:rq fromFile:[NSURL fileURLWithPath:path]] resume];
tuttu47

The issues seems to be that you are trying to use a "streamed request" instead of file. The code works with

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:filePath] progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error){

.... }];

method without any issues. I also found that if you try to use the file data instead of the actual file (with uploadTaskWithRequest: fromData: progress: completionHandler:), the upload fails as explained in Upload tasks from NSData are not supported in background sessions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!