I use AFNetworking
in my app for every request (like login, get data from url, etc).
Take this for example: an user click on the login button and there\
How about using Reachability?
You can check whether you have a plausible reason for trying a connection before you do it.
Looks like the Apple Sample Project for Reachability shows how to get an initial status.
Maybe you could use "Reachability" to determine if the device is connected to the network. Here is the link to the Apple Doc. : Reachability
For example :
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable) {
//Your UIAlertView
}
I use the AFNetworkingOperationDidFinishNotification
.
Every time a http request will fail, the alert pops up and informs the user
- (void)addNetworkObserver
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(HTTPOperationDidFinish:)
name:AFNetworkingOperationDidFinishNotification
object:nil];
}
- (void)HTTPOperationDidFinish:(NSNotification *)notification
{
AFHTTPRequestOperation *operation = (AFHTTPRequestOperation *)[notification object];
if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
return;
}
if (operation.error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection error"
message:@"Missing connection to the internet"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
As of 0.9, AFHTTPClient
actually has network reachability built-in (a simpler interface to Apple's aforementioned Reachability code). Just include the SystemConfiguration
framework and use -setReachabilityStatusChangeBlock:
to specify a response when the reachability state changes.
With AFNetworking
these are the steps that one has to follow in order to take advantage of setReachabilityStatusChangeBlock:
after adding the AFNetworing classes -
SystemConfiguration.framework
to your project#import <SystemConfiguration/SystemConfiguration.h>
AFHTTPClient
in this subclass add below lines of code in init function -[self setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSLog(@"changed %d", status); //your code here }];