I am trying upload image using backgroundSessionConfiguration
and NSURLSessionUploadTask
to keep live upload process in application background mode.
But when i use backgroundSessionConfiguration
, NSURLSessionUploadTask
is not calling delegate method while using defaultSessionConfiguration
it call delegate method.
Here is the code.
//Create a file to upload
UIImage *image = [UIImage imageNamed:@"1.jpg"];
NSData *imageData = UIImagePNGRepresentation(image);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *URLs = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSString *documentsDirectory = [[URLs objectAtIndex:0] absoluteString];
NSString *filePath = [documentsDirectory stringByAppendingString:@"testfile.jpg"];
[imageData writeToFile:filePath atomically:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://file.upload/destination"]];
[request setHTTPMethod:@"PUT"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration: [NSString stringWithFormat:@"testSession.foo.com"]];
config.HTTPMaximumConnectionsPerHost = 1;
session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath]];
[uploadTask resume];
NSLog(@"==%ld",uploadTask.state);
if i change backgroundSessionConfiguration
to defaultSessionConfiguration
, delegate method will call.
Please help me to understand what am i missing.
Thanks, Nitin
uploadTask.state
immediately after starting task. In my experience, background sessions are a bit slower to start. Are you sure it's not firing off later? Did you implementURLSession:task:didCompleteWithError:
? Is it called? – FlubbackgroundSessionConfigurationWithIdentifier
rather than the deprecatedbackgroundSessionConfiguration
, but otherwise I don't see any problem. Make sure that's a valid object and that you're instantiating that only once in your code. Have you tried watching this in Charles to see if anything happens with your destination server. – FlubbeginBackgriundTask...
call somewhere. Generally you use background session or background task, but not both: you want to keep a minimal footprint after use leaves your app to go do something else. – FlubhandleEventsForBackgroundURLSession
; (b) whether that's saving thecompletionHandler
; (c) whether that is restarting the background session with same identifier; (d) whether yourURLSessionDidFinishEventsForBackgroundURLSession
is calling the savedcompletionHandler
. – Flub