AFNetworking not receiving response data - ios

I am using AFNetworking to GET request by posting json object. But i am receiving empty value. I am using the following code.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *params = # {#"email" :user_name, #"password" :pass_word };
[manager GET:HOST_URL parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
NSDictionary *weather = (NSDictionary *)responseObject;
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSLog(#"opstr%#",operation.responseString);
}];
What method i should use. If i use POST, i am getting error saying that "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)
When i use GET i am getting response as empty. I am not sure where i am wrong.
Thanks in advance.

It means that your request response is not a valid json. You can correct the web service to return proper json. Or remove the following line
manager.requestSerializer = [AFJSONRequestSerializer serializer];
because it is converting response to json.
To allow fragments, change the code to following
[manager GET:HOST_URL parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
id json = [NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingAllowFragments
error:&deserializingError];
NSLog(#"JSON: %#", responseObject);
NSDictionary *weather = (NSDictionary *)responseObject;
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSLog(#"opstr%#",operation.responseString);
}];

Related

how to post parameter like {"register_id":"3"} in AFNetworking

i tried it but didn't work in AFNetworking only showing parameters error
but i used postman to check and when i send data via key and value it showing error but from raw data i send {"register_id":"3"}
then it will show me data so how to post parameter like this in AFNetworking.
using This Link
http://www.icubemedia.net/visitorbook/display_all.php
is any one can help me for that how to post that data
log error is:
2015-06-19 14:05:08.078 DemoAFNetworking[72771:1160924]
{"msg":"parameter missing!"}
Indeed there are no parameters missing, the fact that the request worked in Postman was the key. On the one hand, you should be trying to POST to that URL, not GET. On the other hand, since you are sending a JSON, you need the appropriate serializer.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//JSON Serializer
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{#"register_id": #"3"};
[manager POST:#"http://www.icubemedia.net/visitorbook/display_all.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Check this example on how to do a GET with simple parameter with AFNetworking 2.0:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager GET:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
EDIT 1: added JSON serializer ;)

AFNetworking: how to get the response string when failed?

I am using
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
to communicate with the server, and it works great.
But sometimes, there is an error on the server, and it's response is not in json format. My partner wants me to show the error string, but since it went to the failure block, I can hardly get the original response string.
Anyone can help?
You may log operation.responseString line in success and failure block both to get response string of server.
If webservice has some kind of error and provide invalid json or response then log [error description] in failure block.
For reference please check below code snippet.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:120];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:[[NSString stringWithFormat:#"%#",URL]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Response: %#", operation.responseString);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# \n %#", operation.responseString,[error description]);
}];
In the failure block, add these codes:
NSDictionary *userInfo = [error userInfo];
NSString *message = [userInfo objectForKey:#"message"];
I think message is what you need, you can use NSLog to reveal the info.
To take error code(response code) you can use [operation.response statusCode];
Error detail should be here
id responseObject = error.userInfo[kErrorResponseObjectKey];
Referanced from: http://www.splinter.com.au/2014/09/10/afnetworking-error-bodies/

AFNetworking POST Request not working?

This question is already answered at many places but no solution is working for me! I m using code for AFNetworking as following
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer serializer];
NSDictionary *parameters=#{#"Key1":#"Value1",#"Key2":#"Value2"};
// NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"https://www.MyURL.com/index.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Error :
Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x7a2a03b0 {NSErrorFailingURLKey=https://www.MyURL.com/index.php, NSErrorFailingURLStringKey=https://www.MyURL.com/index.php}
I got no luck for above request.
I do not know what is wrong with my code in POST Request, GET Request is working fine in the AFNetworking.
Try this one :
NSDictionary *dictParameters = parameter here
//create url
NSString *strURL = [NSString stringWithFormat:#"url here"];
NSLog(#"loginurl : %#",strURL);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *apiRequest = [manager POST:strURL parameters:dictParameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSData *jsonData = (NSData *)responseObject;
NSError * parsedError = nil;
id *value = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&parsedError];
if (parsedError == nil)
{
//Successfull
}
else
{
NSLog(#"wrong while parsing json data");
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error : %#",[error description]);
}];
//start request right now
[apiRequest start];
EDIT : Just Formatted

JSON error in AFNetworking

I'm trying to use the AFNetworking library to send a post request to an URL like this:
https://m.com/api/2.0/basic/sim_balance.json
That expects a username and password in the URL that are my parameters (as NSDictionary).
The URL gives a JSON back like this:
{
"valid_until": "2011-05-05 22:13:28",
"sms": 0,
"sms_super_on_net_max": 300,
"voice_super_on_net": 0,
"credits": "0.00",
"bundles": [],
"is_expired": true,
"sms_super_on_net": 0,
"voice_super_on_net_max": 3600,
"data": 0
}
This is my request function:
+(void) request:(NSString *)endpoint : (NSDictionary *) parameters
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:endpoint parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
I always get this as error:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x904b7e0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
I validated the JSON and the server is sending valid JSON.
Can someone help me out on this?
To get AFHTTPRequestOperationManager to serialize the request body as JSON, you need to set the value of its requestSerializer:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:....];
If you do not set the requestSerializer property, then the manager object will use x-www-form-urlencoded serialization by default.
Note however that AFHTTPRequestOperationManager will handle JSON in the response body by default.
I found the solution thanks to ester. Also you need to set the basic auth headers right.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"Tom" password:#"test"];
[manager GET:endpoint parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Response data: %#",operation.responseData);
NSLog(#"Response String: %#",operation.responseString);
NSLog(#"Error: %#", error);
}];
}

Differences between sending POST with AFNetworking and curl

I
ve been using AFNetworking 2 with success for some time, but I stumbled upon case where I don't know where to turn my head to. I have to make POST request in order to log in, send credentials alongside and receive JSON back with operation status. For some weird reason sending it via AFNetworking like this:
NSDictionary *params = #{#"login": self.loginField.text, #"password" : self.passField.text};
NSDictionary *data = #{#"data": params};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
//manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:server parameters:#{#"data" : params} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
}];
I have to pack dictionary with parameters as a single "data" parameter. I do get back OK 200, but if I take a look in server logs I see that no data was transferred, which ended up as user not recognized.
But if send with curl this:
curl -d 'data={"login":"xx", "password":"yy"}' http://someurl/api/login/
I got perfectly fine response and in logs I see some actual data. Does anyone know how to deal with such a case?
If it helps, I'm doing it in iPhone simulator, not tested on actual device.
If you have a look at the AFNetworking source code, namely the class AFJSONRequestSerializer, you will see that the serialise function for that serialiser puts the parameters you hand over into the body - and not as an HTTP parameter as you expect.
You should use an AFHTTPRequestSerializer in your case - that will add the parameters as (URL-encoded) HTTP parameters to your URL.
Something like that should work in your case:
// build the JSON parameter string
NSDictionary *params = #{#"login": self.loginField.text, #"password" : self.passField.text};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes]
length:[jsonData length]
encoding:NSUTF8StringEncoding];
// and now send the JSON parameter string as HTTP parameter
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:server
parameters:#{#"data" : jsonString}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
}];

Resources