Skip to content

Instantly share code, notes, and snippets.

@dhilipsiva
Created September 21, 2012 15:55
Show Gist options
  • Save dhilipsiva/3762300 to your computer and use it in GitHub Desktop.
Save dhilipsiva/3762300 to your computer and use it in GitHub Desktop.
Objective-C : A simple REST Json call using AFNetworking
-(void)actionRegister:(UIButton *)btn{
//Yes, I know you can use dictionary, but there is a bug in AFNetworking that fails to set parameters from dictionary. So I am doing it manually here.
NSString *paramStr = [NSString stringWithFormat:
@"firstname=%@"
"&lastname=%@"
"&email=%@"
"&username=%@"
"&password=%@",
firstname.text,
lastname.text,
email.text,
username.text,
password.text];
NSURL *reqURL = [NSURL URLWithString:[AURLString stringByAppendingString:paramStr]];
NSMutableURLRequest *jsonRequest = [NSMutableURLRequest requestWithURL:reqURL];
[jsonRequest setHTTPMethod:@"POST"];
AFJSONRequestOperation *oper = [AFJSONRequestOperation
JSONRequestOperationWithRequest:jsonRequest
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[self.spinner stopAnimating];
NSDictionary *reply = [NSDictionary dictionaryWithDictionary:JSON];
if ([[reply valueForKey:@"success"] boolValue]){
//Account creation successful
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:@"Registered"
message:@"Your Account is successfully registered!"
delegate:Nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alrt show];
}
else{
//Success is 'fail'
NSString *msg = [reply valueForKey:@"msg"];
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:@"Error"
message:msg
delegate:Nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alrt show];
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
//possibly some network error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
}];
[oper start];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment