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?
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.
You can set POST parameters on an NSURLRequest this way:
NSString *username = @"theusername";
NSString *password = @"thepassword";
[request setHTTPMethod:@"POST"];
NSString *usernameEncoded = [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *passwordEncoded = [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *postString = [NSString stringWithFormat:[@"username=%@&password=%@", usernameEncoded, passwordEncoded];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
In other words, you create a query string the same way as if you were passing the parameters in the URL, but set the method to POST
and put the string in the HTTP body instead of after the ?
in the URL.
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