NullPointer
NullPointer

Reputation: 195

AFNetworking GET parameters with JSON (NSDictionary) string contained in URL key parameter

This JSON string has to be sent:

{
"dashboard": "compact",
"theme": "dark",
"show_side_bar": "yes"
}

to a REST API using GET method in this format (since server retrieves data with this PHP code $_GET["setting"]) with AFHTTPRequestOperationManager, such that the equivalent URL becomes:

http://www.examplesite.com/api/change_setting?setting={ "dashboard" : "compact", "theme" : "dark", "show_side_bar" : "yes" }

When I create an NSDictionary of parameters in AFHTTPRequestOperationManager's GET:parameters:success:failure: which adds the url key parameter to the parameter dictionary itself like this:

{
  "setting": {
    "dashboard": "compact",
    "theme": "dark",
    "show_side_bar": "yes"
  }
}

In short only the JSON string must be encapsulated in setting parameter NOT as object of setting in a JSON string.

Edit: Here's the code:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{
                             kSettingDashboard: @"compact",
                             kSettingTheme: @"dark",
                             kSettingShowSideBar: @"yes"
                             };

[manager GET:kURLChangeSetting
  parameters:[NSDictionary dictionaryWithObject:parameters forKey:@"setting"]
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         // code
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         /// code
     }];

Upvotes: 1

Views: 1509

Answers (2)

Gaurav Parmar
Gaurav Parmar

Reputation: 457

you can ask the php developer to change the GET To request so that you send data in POST so that your data can be sent in large amount and securely also

Upvotes: 0

Bannings
Bannings

Reputation: 10479

Try this:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSString *parametersString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

[manager GET:kURLChangeSetting
  parameters:@{@"setting" : parametersString}
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         // code
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         /// code
     }];

Upvotes: 5

Related Questions