Ios – Adding parameters to request with AFNetworking

afnetworkingios

I recently followed the CodeSchool course to learn iOS and they recommend using AFNetworking to interact with the server.

I am trying to get a JSON from my server, but I need to pass some parameters to the urls. I do not wish to add these parameters to the URL since they contain user passwords.

For a simple URL request I have the following code:

NSURL *url = [[NSURL alloc] initWithString:@"http://myserver.com/usersignin"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation
       JSONRequestOperationWithRequest:request
               success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                        NSLog(@"%@",JSON);
               } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                        NSLog(@"NSError: %@",error.localizedDescription);             
               }];

[operation start];

I have checked the documentation of NSURLRequest but didn't get anything useful from there.

How should I pass a username and password to this request to be read in the server?

Best Solution

You can use an AFHTTPClient:

NSURL *url = [[NSURL alloc] initWithString:@"http://myserver.com/"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];

NSURLRequest *request = [client requestWithMethod:@"POST" path:@"usersignin" parameters:@{"key":@"value"}];

AFJSONRequestOperation *operation = [AFJSONRequestOperation
   JSONRequestOperationWithRequest:request
           success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                    NSLog(@"%@",JSON);
           } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                    NSLog(@"NSError: %@",error.localizedDescription);             
           }];

[operation start];

Ideally, you'd subclass AFHTTPClient and use its postPath:parameters:success:failure: method, instead of creating an operation manually and starting it.

Related Question