Lovely Lovely - 1 month ago 15
Objective-C Question

POST dictionary on server

How to POST dictionary on server using NSURLSession in objective c.I have gone through tutorials...but still the concept is not clear.Kindly explain and help how this can be done?I have attached the code as suggested.Kindly check it and explain.

-(void)sendDetailsToServer:(NSDictionary *)details withToken:(NSString*)token{


NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session = [NSURLSession sessionWithConfiguration: sessionConfig delegate: self delegateQueue: [NSOperationQueue mainQueue]];


NSData* jsonData = [NSJSONSerialization dataWithJSONObject:details options:0 error:nil];

NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil]);

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/detailurl",Url, token]]];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];


currentSerType = SendUserUpdateDetails;


NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
[dataTask resume];


}






- (IBAction)saveAction:(UIBarButtonItem *)sender {


NSLog(@"the values stored in dictionary are %@",_userDetailsDictionary);

[[NSUserDefaults standardUserDefaults] setObject:_userDetailsDictionary forKey:@"UpdatedDetails"];

[[NSUserDefaults standardUserDefaults] synchronize];

Network * connection = [Connection sharedConnection];
connection.delegate = self;
[connection sendUserUpdatedDetailsToServer:_userDetailsDictionary];



}

Answer

if want to know whether the data is successfully submitted to server or not. Just use,

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSHTTPURLResponse *serverResponse = (NSHTTPURLResponse*)response;
    if (serverResponse.statusCode == 200) {
        NSLog(@"Data successfully submitted in server");
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    } else {
        NSLog(@"%@", error.localizedDescription);
    }

}];
Comments