Friday, July 24, 2015

iOS NSURLSession - Uploading Content

Apple has described NSURLSession as both a new class and a suite of classes. There’s new tools to upload, download, handle authorization, and handle just about anything in the HTTP protocol. 

NSURLSession is made using NSURLConfiguration and an optional delegate. After creating the session, the networking needs are satisfied by creating NSURLSessionTasks. 

There are 3 NSURLSessionConfigurations

1. defultSessionConfiguration : This is most like NSURLConnection. This configuration object uses a global cache, cookie and credential storage objects. 
2. ephemeralSessionConfiguration : this configuration is for private sessions and has no persistent storage for cache, cookie or credential storage objects. 
3. backgroundSessionConfiguration : this is the configuration to use if we are going to create the session from background such as remote notification received. i.e. basically when app is suspended. 

NSURLConnection does their most of the jobs by their minions NSURLSessionTasks. 

For eg. To Upload a zip File content, below to be done. Very Important that to specify the Content-Type. Else, the session seems to be sending the data as Query parameters as seen from the Java Servlet end. 

-(void) uploadImageData
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *logFilePath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,@“file.zip”];

    NSData *logData = [[NSFileManager defaultManager] contentsAtPath:logFilePath];
    
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfiguration.HTTPAdditionalHeaders = @{@"_username": @"testuser"};
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
    NSURL *url = [NSURL URLWithString:@"https://myserverurl.com/upload”];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request addValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = logData;
    request.HTTPMethod = @"POST";
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSLog(@"Error :%@",error);
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        
        NSDictionary *dict = httpResponse.allHeaderFields;
        NSLog(@"All Headers :%@",dict);

    }];
    [postDataTask resume];
}

References:

No comments:

Post a Comment