I want to use AFNetworking more specifically AFJSONRequestOperation in a project to allow for easy async calls. I quickly tried using the sample code from AFNetworking GitHub Page
NSURL *url = [NSURL URLWithString:#"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"App.net Global Stream: %#", JSON);
}
failure:nil];
[operation start];
Which works fine, But when I use the URL for MetOffice Datapoint it crashes, I believe this might be because of the encoding type of the JSON feed being NSISOLatin1StringEncoding which causes a problem with NSJSONSerialization
The way I currently handle this is
NSString *string = [NSString stringWithContentsOfURL:kMetOfficeAllSites encoding:NSISOLatin1StringEncoding error:&error];
NSData *metOfficeData = [string dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:metOfficeData options:kNilOptions error:&error]
But how do I handle this situation with AFJSONRequestOperation?
Thanks in Advance
Related
I am trying to perform GET requests that returns JSON string from a web-service using AFNetworking but I am receiving the following error from AFNetworking 1.3.3
#"JSON text did not start with array or object and option to allow fragments not set."
and here is my JSON which is a valid JSON string , I used many online validators to make sure
"{\"ErrorCode\":0,\"VerCode\":\"8595\"}"
AFNetworking Code that is not working
NSString *urlString = [BASE_URL stringByAppendingString:paramseters];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET"
path:urlString
parameters:nil];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *jsonDic = (NSDictionary *)JSON;
success(jsonDic);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
CPError *cpError = [CPError CPErrorWithErrorCode:error.code errorDesc:error.localizedDescription];
failure(cpError);
}];
[operation start];
I was able to parse the JSON into NSDictionary using the below code but I want to be able to use AFNetworking in order to make use of it's built in features , is there a way to make AFNetworking understands my JSON string ?
NSURL *url = [NSURL URLWithString:#"http://103.1.173.60/ims-mobile-wcf/MobileWCF.svc/AddUpdateMobileClient/123123/443da4444/1/1"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:120];
[request setHTTPMethod:#"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(#"%#",connectionError);
NSError *error = nil;
NSString *JSONString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSDictionary *JSONDictionary =
[NSJSONSerialization JSONObjectWithData: [JSONString dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
}];
I'll take a stab and say the reason is that the response string appears to be in quotes, if this is the case then the error is very clear - the Fragments option is not set. Do a a global search for "JSONReadingOptions" and you'll find the place in AFNetworking where the response is serialized into a foundation object (in version 1.3 it's AFJsonRequestOperation line 79, it looks like your using 2.0) is basically exactly what you are doing manually. If you do as arturdev suggests and set the reading options to be NSJSONReadingAllowFragments it should work.
Try:
AFJSONRequestOperation *operation = ...
operation.JSONReadingOptions = NSJSONReadingAllowFragments;
[operation start];
This is wrong:
NSError *error = nil;
NSString *JSONString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSDictionary *JSONDictionary =
[NSJSONSerialization JSONObjectWithData: [JSONString dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
JSONObjectWithData: does not return an NSString, it returns an object: NSArray or NSDictionary, in your case a NSDictionary
Just use:
NSError *error = nil;
NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
I've inherited a project and am implementing AFNetworking and reading the docs it sounds great and much simpler than the current code. I have a url with json data so I'm doing the following, but getting the failure block and no idea why. I'm sure it's there, but how can I dig into AF and log the responses to determine failure reason. I know the url works, but perhaps its hitting the url but having trouble parsing?
NSString *listURL = [NSString stringWithFormat:GET_LIST,BASE_URL];
NSURL *url = [NSURL URLWithString:briefListURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest: request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.list = [NSArray arrayWithArray:(NSArray *)JSON];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
[self listOperationDidFail];
}];
thanks to #Larme this worked:
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { NSLog(#"Error: %#", error); }
also, to answer my own issue above with text/plain. just add this before setting up operation:
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:#"text/plain"]];
I need live currency rates. I am using a Google API available in the URL
http:://www.google.com/ig/calculator?hl=en&q=1USD=?INR
Whenever am hitting that URL using json parsing, then response data getting nil. I am not getting what is the exact error in that code
#define openexchangeURl #"http://www.google.com/ig/calculator?hl=en&q=1USD=?INR"
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:openexchangeURl]];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
values =[responseString JSONValue];
This will get you live rates:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://rate-exchange.appspot.com/currency?from=USD&to=INR&q=1"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSDictionary *parsedDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
CGFloat value = [parsedDict[#"rate"] floatValue];
NSLog(#"Value: %f", value);
}];
The JSON response from that api looks like this:
{
to: "INR",
rate: 54.8245614,
from: "USD",
v: 54.8245614
}
Your original request didn't have an NSURLConnection and the response was not valid JSON (did not have double-quoted values for each item in the hash).
How to get urllink data that are stored in database in iphone sdk ?
Use the following Code may be help you.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"Your URL"]]];
// Perform request and get JSON as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"Your Data=%#",response);
id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil];
I'm trying to implement Google OAuth 2 to get access to the Google APIs.
When i try to exchange the code by an access token, it doesn't work.
I use this method to do it.
(void)getAccessTokenwWithCode:(NSString*)code
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[#"https://accounts.google.com/o/oauth2/token" ]];
[request setHTTPMethod:#"POST"];
NSDictionary *postBodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
code, #"code",
#"my_client_id", #"client_id",
#"my_client_secret", #"client_secret",
#"http://localhost", #"redirect_uri",
#"authorization_code", #"grant_type",
nil];
NSString *postBody = [postBodyDic JSONString];
NSData *data = [postBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setHTTPBody:data];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSURLResponse *response, id JSON)
{
NSLog(#"%#", JSON);
}
failure:^(NSURLRequest *request, NSURLResponse *response, NSError *error, id JSON)
{
NSLog(#"ERROR \n%#", error );
}
];
[queue addOperation:operation];
}
I get a 400 error
Anyone can help me to localize the problem?
Thanks in advance.
Since you are using the AFNetworking classes, try using the AFNetworking Extension for OAuth 2 Authentication. I haven't used it, but it looks like what you need.