Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To POST JSON Parameters Using AFNetworking?

how can I POST JSON parameters with AFNetworking? Below is the example JSON format. Thank you in advance.

{
    "application": {
        "identifier": "appDev"
    },
    "sso": {
        "version": 2.0,
        "session_expiry": 43200
    },
    "user": {
        "password": "xxxx~!@",
        "username": "xxx0min"
    },
    "coordinate": {
        "latitude": 10.9948629,
        "longitude": -169.5213749
    }
}

I successfully created a JSON :

NSDictionary *parameters = @{@"application": @{@"identifier": @"appDev"}, @"sso": @{@"version": @"2.0", @"session_expiry":@43200}, @"user": @{@"password":@"xxxx~!@", @"username":@"xxx0min"}, @"coordinate": @{@"latitude":@10.9948629, @"longitude":@-169.5213749}};
like image 603
Mohamad Afiq Avatar asked Dec 23 '15 11:12

Mohamad Afiq


2 Answers

First convert JSON string to NSDictionary:

NSError *error;
NSData *objectData = [@"{\"1\":\"2\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&error];

Then you can send this dictionary with AFNetworking. In version 3 you should use AFHTTPSessionManager:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[manager POST:@"your_URL" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"Complete");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"Fail");
}];
like image 136
Rost Avatar answered Oct 17 '22 13:10

Rost


Finally I found a solution to my problem. What I was doing is making NSDictionary of NSDictionary for my JSON parameters. Below is the full solution code.

NSString *loginURL = @"http://myappdev.dev/login";

 NSDictionary *parameters = @{@"application": @{@"identifier": @"appDev"}, @"sso": @{@"version": @"2.0", @"session_expiry":@43200}, @"user": @{@"password":@"xxxx~!@", @"username":@"xxx0min"}, @"coordinate": @{@"latitude":@10.9948629, @"longitude":@-169.5213749}};

    NSLog(@"params : %@", parameters);

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:loginURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON Successsss: %@", responseObject);
        NSLog(@"operation Successsss: %@", operation);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error laaa: %@", error);
    }];
like image 29
Mohamad Afiq Avatar answered Oct 17 '22 14:10

Mohamad Afiq