I\'m trying out the new fancy iOS 7 background uploading using NSURLSessionUploadTask and it seems to work when I run with defaultSessionConfiguration, but once I try backgr
As requested, background uploading example. Be sure to implement NSURLSessionDelegate and NSURLSessionTaskDelegate as needed.
NSMutableArray *unsentPhotos = (NSMutableArray*)[sendingMessage objectForKey:@"unsentPhotos"];
TMessage *message = (TMessage*)[sendingMessage objectForKey:@"message"];
message.sendStatus = MS_PENDING_IMAGE_UPLOAD;
for (int i = 0; i < [unsentPhotos count]; i++) {
NSString *fileName = [unsentPhotos objectAtIndex:i];
NSLog(@"Initiating file upload for image %@", fileName);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *srcImagePath = [NSString stringWithFormat:@"%@/messageCache/%@", [paths objectAtIndex:0], fileName];
NSString *dataSrcImagePath = [srcImagePath stringByAppendingString:@".tmp"];
//Encode file to data
NSData *imageData = [NSData dataWithContentsOfFile:srcImagePath];
if (!([imageData writeToFile:dataSrcImagePath atomically:YES])) {
NSLog(@"Failed to save file.");
}
//Prepare upload request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://blah.com"]];
[request setHTTPMethod:@"PUT"];
[request setValue:globalAPIToken forHTTPHeaderField:@"access_token"];
[request setValue:[AppDelegate getMyUserID] forHTTPHeaderField:@"userid"];
[request setValue:[NSString stringWithFormat:@"%d", message.teamID] forHTTPHeaderField:@"teamId"];
[request setValue:[NSString stringWithFormat:@"%d", message.emailID] forHTTPHeaderField:@"messageId"];
[request setValue:fileName forHTTPHeaderField:@"fileName"];
[request setValue:@"1" forHTTPHeaderField:@"basefile"];
if (i == 0) {
//If this is the first upload in this batch, set up a new session
//Each background session needs a unique ID, so get a random number
NSInteger randomNumber = arc4random() % 1000000;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration: [NSString stringWithFormat:@"testSession.foo.%d", randomNumber]];
config.HTTPMaximumConnectionsPerHost = 1;
session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
//Set the session ID in the sending message structure so we can retrieve it from the
//delegate methods later
[sendingMessage setValue:session.configuration.identifier forKey:@"sessionId"];
}
uploadTask = [session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@", dataSrcImagePath]]];
[uploadTask resume];
}