1

I have this structure in a web service:

{
    "user":
    {
        "email":"prueba@hotmail.com",
        "password":"12345678",
        "objectId":"2334jklwf",
        "token":"12334023ijrdadfsdoifj"
    }
}

I need to make an HTTP POST using NSURLSession (iOS 9). So I need to create a dictionary with a key called 'user' and inside that key another dictionary with all the keys shown, right? And what is the way to POST it?

iBhavin
  • 1,261
  • 15
  • 30
abnerabbey
  • 125
  • 1
  • 10

2 Answers2

0

Following function works for me you can try with it. You can set header values in NSURLSessionConfiguration object.

- (void)callWS {

    NSURL * url = [NSURL URLWithString:@"Your URL"];
    NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession * session = [NSURLSession sessionWithConfiguration:config];


    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    request.HTTPMethod = @"POST";

    NSDictionary * dicData = [NSDictionary dictionaryWithObjectsAndKeys:@"prueba@hotmail.com",@"email",@"12345678",@"password",@"2334jklwf",@"objectId", nil];


    NSDictionary *dictionary = @{@"user": dicData};
    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
                                                   options:kNilOptions error:&error];

    if (!error) {

        NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
                                                                   fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {

                                                                       // Handle response here
                                                                   }];

        [uploadTask resume];
    }
}
Abhishek Sharma
  • 3,283
  • 1
  • 13
  • 22
-1

you can set json at body of request

request.HTTPMethod = "POST"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            if let data = param?.JsonStringWithPrettyPrint(){
                request.HTTPBody = NSString(string: data).dataUsingEncoding(NSUTF8StringEncoding)
            }

In there: param is your dictionary and JsonStringWithPrettyPrint is a extentsion of NSDictionary:

extension NSDictionary  {
    func JsonStringWithPrettyPrint()-> String? {
        do{
            let data = try NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions.PrettyPrinted)
            return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
        }catch{
            return nil
        }
    }
}
Nguyen Hoan
  • 1,583
  • 1
  • 11
  • 18