Reputation: 221
I figured out how to pass params using AFnetworking but I am having a hard time trying to figure out how to pass body as part of my API call. Currently this is what I do:
- (void)authenticateUser:(NSString *)username
password:(NSString *)password
success:(void (^) (NSString *accessToken))success
failure:(RequestFailureBlock)failure
{
NSString *authURL = @"http://someurlforauthentication";
NSDictionary *parameters = @{@"username" : username,
@"password" : password };
[self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[self POST:authURL parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject){
NSString *accessToken = responseObject[@"access_token"];
// Store Access Token
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:accessToken forKey:APIAuthorizationToken];
[defaults synchronize];
NSLog(@"Hello %@", accessToken);
success(accessToken);
} failure:failure];
}
What I need to do is not pass any params and instead pass a body with a json string containing login credentials. Something like this
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// Body
const char bytes[43] = "{\n \"username\": \"max\",\n \"password\": \"pass\"\n}";
request.HTTPBody = [NSData dataWithBytes:bytes length:43];
Thanks in advance.
Upvotes: 3
Views: 6849
Reputation: 906
Using AFJSONRequestSerializer and AFJSONResponseSerializer you can do what you want. Then just use the code you were using to post. The whole process should look like follows:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
NSDictionary *parameters = @{@"test": @"this is a test"};
[manager POST:@"http://localhost:8080/TestRequest/test" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"%@",[responseObject description]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"%@",[error localizedDescription]);
}];
Upvotes: 9