AFNetworking JSON Response caching: offline mode - ios

I am creating an iOS Application working in offline mode by using a AFNetworking library.
To manage a HTTP request I have defined a AFHTTPRequestOperationManager
- (AFHTTPRequestOperationManager *)requestOperationManager
{
if (!_requestOperationManager)
{
_requestOperationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:SERVICE_BASE_URL]];
}
return _requestOperationManager;
}
To load a HTTP request I have defined a method:
- (void)loadRequest
{
if (!self.internetConnectionAvaliable)
{
self.requestOperationManager.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
}
NSString *url = SERVICE_METHOD_URL;
NSDictionary *parameters = #{#"password" : USER_PASSWORD, #"username" : USER_NAME};
[self.requestOperationManager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *htmlString = [NSString stringWithFormat:#"%#", [responseObject objectForKey:#"view"]];
[self.webView loadHTMLString:htmlString baseURL:nil];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ERROR!!!" message:#"ERROR!!!" delegate:nil cancelButtonTitle:#"CANCEL" otherButtonTitles:nil];
[alertView show];
}];
}
When internet connection is enabled, AFNetworking loads desired data perfectly.
When internet connection is disabled, AFNetworking doesn't load any data. This makes me think, that data caching doesn't work as it should!
Does anyone knows why?
How to fix it?

Related

Unable to call sportsdatallc api for get match schedule

I tried lots but getting this error while calling this api for getting match schedule using this
- (IBAction)getButtonPressed:(id)sender
{
NSString *string = [NSString stringWithFormat:#"https://api.sportsdatallc.org/nba-Trial(t)1/ru/games/2014/reg/schedule.json?api_key=qgdmf6egtuf5guy9pdvk5ydf"];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(#"url is %#",url);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
NSLog(#"%#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
getting this error
Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: server error (596)" UserInfo=0x7994db10 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x799335b0> { URL: https://api.sportsdatallc.org/nba-Trial(t)1/ru/games/2014/reg/schedule.json?api_key=qgdmf6egtuf5guy9pdvk5ydf } { status code: 596, headers {
Connection = "keep-alive";
"Content-Length" = 30;
"Content-Type" = "text/xml";
Date = "Fri, 20 Mar 2015 08:55:01 GMT";
Server = "Mashery Proxy";
"X-Mashery-Error-Code" = "ERR_596_SERVICE_NOT_FOUND";
} }, NSErrorFailingURLKey=https://api.sportsdatallc.org/nba- Trial(t)1/ru/games/2014/reg/schedule.json?api_key=qgdmf6egtuf5guy9pdvk5ydf, NSLocalizedDescription=Request failed: server error (596), com.alamofire.serialization.response.error.data=<3c68313e 35393620 53657276 69636520 4e6f7420 466f756e 643c2f68 313e>, NSUnderlyingError=0x7994eb90 "Request failed: unacceptable content-type: text/xml"}
I am using this website api:
http://developer.sportsdatallc.com/docs/NBA_API
Details of using this api:
Daily Schedule
Schema
Syntax:
http(s)://api.sportsdatallc.org/nba-[access_level][version]/schema/schedule-v2.0.xsd?api_key=[your_api_key]
Schema Example:
Feed
Syntax:
http(s)://api.sportsdatallc.org/nba-[access_level][version]/[locale]/games/[year]/[month]/[day]/schedule.xml?api_key=[your_api_key]
Parameter Format Notes
[access_level] = Production (p), Trial (t)
[version] = whole number (sequential, starting with the number 1)
[year] = Year in 4 digit format (YYYY)
[month] = Month in 2 digit format (MM)
[day] = Day of the month in 2 digit format (DD)
[format] = xml, json
Optional Parameters
[locale] = ru (russian), zh (simplified chinese)
In -[AFHTTPRequestOperationManager initWithBaseURL:], you will find that the responseSerializer property is set to an instance of AFJSONResponseSerializer. .
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:myURL];
To get the functionality you want(delivering a parsed XML model back to your callback as the responseObject), simply set the responseSerializer property to an instance of AFXMLResponseSerializer
manager.responseSerializer = [AFXMLResponseSerializer new];
Sample Code:
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:myURL];
manager.responseSerializer = [AFXMLResponseSerializer new];
[manager GET:#"http://www.example.com/feed" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Data: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

AFNetworking fail with response.statusCode 0

I want to get address from latitude and longitude with GoogleGEO CODING (EX URL = http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true_or_false )
So I want to get JSON from that page by AFNetworking.
It's my code below :
IBAction)reLocation:(UIButton*)sender
{
if(sender.tag==1)
{
NSArray *gpsValue = [self getGPS];
float lat = [[gpsValue objectAtIndex:0] floatValue];
float lon = [[gpsValue objectAtIndex:1] floatValue];
NSString *string = [NSString stringWithFormat:#"%#%#,%#&sensor=true_or_false",GEOCODING_URL,[NSString stringWithFormat:#"%f", lat],[NSString stringWithFormat:#"%f",lon]]; // NSString *str = [NSString stringWithFormat:#"%f", myFloat];
NSLog(string);
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"AFNetworking success");
NSDictionary *location = (NSDictionary *)responseObject;
// 3
self.title = #"JSON Retrieved";
//[self.tableView reloadData];
NSLog(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"AFNetworking failure");
switch (operation.response.statusCode) {
case 400:
// Do stuff
NSLog(#"error 400");
break;
default:
NSLog([NSString stringWithFormat:#"%ld",(long)operation.response.statusCode]);
break;
}
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}}
But when I click my button, always afnetworking fails and log shows 0 for status code.
I also got url log that i put in
i already checked that url is not problem (it shows json in working order)
I debug with simulator!
Is there something I miss ?

AFHTTPSessionManager or AFHTTPOperationManager been skipped, not even executing

I'm new to IOS development and was doing something related to dynamic data request through a 3rd party api using AFNetworing, I assume this is the good way to do networking in IOS?
One issue I have so far is I have two AFHTTPSessionManager in two different class implementation files. When I ran the application, the first one executes successfully. but the second one is not working and the problem is in debug mode, I can see that the
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:PLACE_DETAIL_URL
parameters:#{ #"key": APPLICATION_KEY,
#"placeid": placeid,
#"extensions": #"review_summary"
}
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#", responseObject);
placeDetail = [[NSDictionary alloc] initWithDictionary: (NSDictionary *) [responseObject objectForKey:#"result"]];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Places"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
is not even executing. It's been skipped for some reason. Is this a bug or I can only have on AFHTTPSessionManager or AFHTTPOperationManager at a time?
P.S.
debug gif posted here for clear idea.
thanks for all your help.

AFNetworking fails to create a request on a GET request

I'm trying to make a get request to a restful service. This request has worked for the last 3 weeks when I was using a request without a request manager. As soon as I added a request manager because I wanted to send a dictionary of parameters, the code keeps crashing with the error:
'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: urlRequest'
My code is as follows. The commented out code still works if I uncomment it and replace the new code with it. Why am I able to make a request from that URL but not with AFNetworking?
NSString *URLForSend = [NSString stringWithFormat:#"%#%#/", ([_remoteDownloadURLString stringByAppendingString:_getFilesJsonURLString]),_userName ];
NSURL *URL = [NSURL URLWithString:URLForSend];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
self.downloadJsonRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request];//this works to create a a afhttprequestoperation, with the same url
_downloadJsonRequest.responseSerializer =
[AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
__unsafe_unretained typeof(self) weakSelf = self;
NSMutableDictionary *mutDictForSend = [[NSMutableDictionary alloc] initWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:#"tokenInfo"]];
[mutDictForSend removeObjectForKey:#"success"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
[manager GET:URLForSend parameters:mutDictForSend success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#", responseObject);
weakSelf.jsonArrayForCaching = responseObject;
[[NSNotificationCenter defaultCenter] postNotificationName:kBIDContentEndingSync object:weakSelf];
[weakSelf gotNewJson:responseObject];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Request Failure Because %#",[error userInfo]);
}];
/*
[_downloadJsonRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#", responseObject);
weakSelf.jsonArrayForCaching = responseObject;
[[NSNotificationCenter defaultCenter] postNotificationName:kBIDContentEndingSync object:weakSelf];
[weakSelf gotNewJson:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Request Failure Because %#",[error userInfo]);
}];
[[NSNotificationCenter defaultCenter] postNotificationName:kBIDContentStartingSync object:self];
[_downloadJsonRequest start];
*/
I'd suggest replacing the line:
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
With
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
The latter calls initWithBaseURL, which does some configuration of the AFHTTPRequestOperationManager, that just calling [[AFHTTPRequestOperationManager alloc] init] does not appear to do.
If you're still having issues even doing that, I'd suggest adding Exception Breakpoint to identify precisely where this exception is taking place.
OK, this was a tough one, but it turns out that requestOperationManager is a singleton so I should not have initialised him, but call its instance...

iOS, How to like a page on facebook?

is there a way to like a page on a button Click.
I've tried many snippets like this one
NSURL *baseURL = [NSURL URLWithString:#"https://graph.facebook.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
NSString *link = [NSString stringWithFormat:#"/%#/likes", #"6783623567"];
NSDictionary *params = #{#"access_token" : [[[FBSession activeSession] accessTokenData] accessToken]};
[httpClient postPath:link parameters:params success:^(AFHTTPRequestOperation *op, id result) {
NSLog(#"result %#", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error %#", error);
}];
but it fails with "Application does not have the capability to make this API call.","type":"OAuthException","code":3".
what I'm doing now is to open the link inside a webview.
Everything here for the code, and here for the publishing actions on Facebook, such as likes... :)

Resources