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}};
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");
}];
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);
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With