statusCode property not set AFJSONRequestOperation - afnetworking

I am using the following code to make a http request and get json response back from a server. However when I look at the response's statusCode, I get the error that statusCode property is not set. What needs to be done to set the statusCode property in response.
NSString * my_url_string = #"http://link-to-my-server";
NSURL *url = [NSURL URLWithString:my_url_string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
if (response.statusCode == 200){
//I GET AN AERROR THAT statusCode IS NOT SET

Error notwithstanding, AFNetworking already made the check for a successful status code with its success/failure completion block distinction. That is to say, unless you want to differentiate between different successful status codes (200, 201, 204, etc.), you don't need to do this check yourself.

Related

how to get responseString when JSON failed with AFJSONRequestOperation

I'm having difficulties to get responseString when server failed to send a valid JSON response (fe. php echos some temp variable or something went wrong). I am using AFJSONRequestOperation from AFNetwoking like this:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
NSLog(#"object: %#", responseObject);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseString) {
NSLog(#"failure: %#", responseString);
}
];
responseString is case of failure is always nil. When I tried to read the documentation (http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFJSONRequestOperation.html#//api/name/JSONRequestOperationWithRequest:success:failure:) I've found that there is written that failure gets three arguments (but in reality four, the fourth being always nil). Is there any simple way to get the response as a string in that case?
If responseString is nil, then you either didn't receive any data from the server, or the data could not be used to create a valid NSString object.
By the sound of your Cocoa error 3840, which corresponds to an NSJSONSerialization error, my guess is that the server was indeed sending back an empty response.

AFNetworking disable caching

I'm trying to get a JSON file from a server then display it in a table, this works fine, however, for some reason AFNetworking is caching the JSON file even after a app restart.
How can I disable this?
NSURL *url = [NSURL URLWithString:#"http://?json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject)
{
self.dataget = [responseObject objectForKey:#"data"];
[self.tableView reloadData];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
{
[HUD hideUIBlockingIndicator];
}];
[operation start];
The json file is probably not cached server side:
Cache-Control: no-cache[CRLF]
Cache behavior can be set on NSMutableURLRequest objects, with setCachePolicy:. Otherwise, the built-in shared NSURLCache will respect the caching behavior defined by the server (which I would recommend tuning and taking advantage of, rather than outright disregarding).
AFNetworking doesn't do any caching. Also, the "Cache-Control" HTTP header tells the client not to cache the page (ie. AFNetworking), not the server.
It sounds like your server is caching the JSON page.
AFNetworking doesn't cache anything. You should probably check the cache control headers of the response. If i am not wrong then your server is sending some cache control headers which NSUrlConnection is taking into consideration. I would recommend you to set the caching policy of NSURLRequest to NSURLRequestReloadIgnoringLocalCacheData before making request to server

AFNetworking getting HTML from rails

I am using AFNetworking to get JSON data from the server, but I am only getting back HTML and an error that says the following:
Expected content type {(
"text/json",
"application/json",
"text/javascript"
)}, got text/html, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7592470>}
The code is as follows:
NSURL *url = [NSURL URLWithString:#"http://127.0.0.1:3000/games"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *req, NSHTTPURLResponse *response, id jsonObject){
NSLog(#"Response: %#", jsonObject);
}
failure:^(NSURLRequest *req, NSHTTPURLResponse *response, NSError *error, id jsonObject){
NSLog(#"Error: %#", error);
}];
[operation start];
I am using rails and the server sends back JSON when I access the page with curl. I want to force application/json to be requested, am I doing this wrong?
You probably need to tell the server what content type you want back.
Here's a common fix for this issue:
NSURL *url = [NSURL URLWithString:#"http://127.0.0.1:3000/games"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
If this doesn't work, you'll need to step through your server code to determine under what conditions it'll return JSON instead of HTML.

How to add custom header to AFNetworking on a JSONRequestOperation

Hi, I have the following code accessing a URL:
NSString * stringURL = [NSString stringWithFormat:#"%#/%#/someAPI", kSERVICE_URL, kSERVICE_VERSION];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
completionHandler(JSON, nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
completionHandler(nil, error);
}];
But I want to pass the user token as a parameter on HEADER, like X-USER-TOKEN.
Cant find it on AFNetworking documentation, should I change the operation type?
Use AFHTTPClient or subclass it!
You can set default headers with -setDefaultHeader:value: like this :
[self setDefaultHeader:#"X-USER-TOKEN" value:userToken];
You can check the documentation
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue: #"X-USER-TOKEN" forHTTPHeaderField:#"< clientToken >"];
[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]
I did this :)
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Token token=\"%#\"", _userObj.oAuth] forHTTPHeaderField:#"Authorization"];
If you have a layer of abstraction, let's say APIManager,
then you should do the following inside a particular method
[[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:#"X-Register"];

AFNetworking - iOS Getting JSON When PHP Prints It

I have just started using AFNetworking, but I can't seem to figure out how to get the following to work.
My URL points to a PHP file which has printed out data it retrieved from a database as JSON, but with AFNetworking I get the "Expected Content Type" error.
My code is the following but with a different URL.
NSURL *url = [NSURL URLWithString:#"http://www.example.com/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
NSLog(#"JSON: %#", [json valueForKeyPath:#"results"]);
} failure:nil];
[operation start];
I figured it out! :D
<?php header("Content-type: text/json"); ?>
Put this at the top of your page before anything is printed on the screen and AFNetworking will recognise it as JSON
#Ashley Thanks for sharing this. I had the same problem and this resolved it. However it should be
header("Content-type: application/json");
and not as you state

Resources