Rotem S
Rotem S

Reputation: 63

AFNetworking JSON request not working

I'm trying to start this operation and its not even getting to the NSLOG. I guess its something with my stringUrl, maybe its not suppose to work like this?

This is my code:

NSString *stringUrl = [[NSString alloc]initWithFormat:@"http://example.com/add_user.php?username=%@&password=%@&country=%@&email=%@",[self.usernameTextField text],[self.passwordTextField text], countrySelected, [self.emailTextField text]];

NSURL *url = [NSURL URLWithString:stringUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSDictionary *dict = JSON;
    NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"item"]);
} failure:nil];

[operation start];

Edit: this is what i got from the failure block:

Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {( "text/json", "application/json", "text/javascript" )}, got text/html" UserInfo=0xa2b4300 {NSLocalizedRecoverySuggestion={"type":"1","item": "User added successfully."} , AFNetworkingOperationFailingURLRequestErrorKey=http://EXAMPLE.com/add_user.php?username=aaasafasfasf&password=aaa&country=Angola&email=aaaasfasfasfasfasf>, NSErrorFailingURLKey=http://EXAMPLE.com/add_user.php?username=aaasafasfasf&password=aaa&country=Angola&email=aaaasfasfasfasfasf, NSLocalizedDescription=Expected content type {( "text/json", "application/json", "text/javascript" )}, got text/html, AFNetworkingOperationFailingURLResponseErrorKey=}

Upvotes: 1

Views: 3294

Answers (1)

Valent Richie
Valent Richie

Reputation: 5226

In order to get into the success block of the AFJSONRequestOperation, you also need to adhere to the correct content type to be sent by the server. Currently your server is returning text/html content type as the response, hence it goes into the failure block.

As the failure block message suggests, change the content type returned to be text/json or application/json since you are using the AFJSONRequestOperation.

For PHP, you can change the content type returned by following the answer in this question: How to change content type in php?

You can just add one additional line below your existing header lines:

header('Content-Type: text/json');

No need to replace existing header lines unless there is a header line to set content type into something else other than text/json or application/json.

Upvotes: 4

Related Questions