I've setup a JSON post with AFNetworking
in Objective-C and am sending data to a server with the following code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"name": deviceName, @"model": modelName, @"pin": pin};
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"Content-Type" forHTTPHeaderField:@"application/json"];
[manager POST:@"SENSORED_OUT_URL" parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"JSON: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error: %@", error);
}];
I'm receiving information through the same request, and want to send the data to a NSString
. How would I go about doing that with AFNetworking
?
In my case, it's looks like (maybe it can helps)
Also would be great to check type of response object (like https://stackoverflow.com/a/21962445/3628317 answer)
responseObject
is either an NSArray or NSDictionary. You can check at runtime usingisKindOfClass:
:If you really need the string of the JSON, it's available by looking at
operation.responseString
.In this case, when the web service responds with
JSON
, theAFNetworking
will do the serialization for you and theresponseObject
will most likely be either aNSArray
orNSDictionary
object.Such an object should be more useful for you than string with
JSON
content.I find it works best to subclass AFHTTPClient like so:
The important bits are:
Then you can use it like so:
The beauty of this is that your responseObject is automatically JSON-parsed into a dictionary (or array) for you. Very clean.
(this is for afnetworking 1.x)