Kiran P Nair
Kiran P Nair

Reputation: 2021

how to pass a dictionary using NSURLSession in post method?

I do not know how to pass values in dictionary into server using NSURLSession via POST. Please help me to solve this problem.

My dictionary contains contact information (name and phone number only), where the key is the person's name and the value is their phone number.

I have sample code using nsurl connection - how can I convert it to use NSURLSession?

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://holla.com/login"]];

request.HTTPMethod = @"POST"; [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"212333333",@"ABCD",@"6544345345",@"NMHG", nil];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Upvotes: 0

Views: 3946

Answers (1)

Kiran P Nair
Kiran P Nair

Reputation: 2021

I solve the problem by using the following method:

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL * url = [NSURL URLWithString:[ NSString stringWithFormat:@"http://xxxx.com/login/save_contact"]];;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];

NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:@"212333333",@"ABCD",@"6544345345",@"NMHG",
                         nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];


NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)

{       
    
    if(error == nil)
    {
        NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
        NSLog(@"Data = %@",text);
    }
    
}];

[postDataTask resume];

Upvotes: 4

Related Questions