AFNetworking and No Internet Connection scenario

24,515

Solution 1

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.

Solution 2

With AFNetworking these are the steps that one has to follow in order to take advantage of setReachabilityStatusChangeBlock: after adding the AFNetworing classes -

  1. Add SystemConfiguration.framework to your project
  2. In pch file add #import <SystemConfiguration/SystemConfiguration.h>
  3. Assuming that you have a subclass of AFHTTPClient in this subclass add below lines of code in init function -
[self setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"changed %d", status);
        //your code here
    }];

Solution 3

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
}

Solution 4

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];
   }
}
Share:
24,515

Related videos on Youtube

Fred Collins
Author by

Fred Collins

Updated on January 06, 2020

Comments

  • Fred Collins
    Fred Collins over 4 years

    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's no connection, how to instantly display a UIAlertView that says the error? The only way is to wait the request timeout and execute the failure block? Isn't there a way that instantly check if there's connection or not?

    Thanks!

  • smparkes
    smparkes over 12 years
    For any case where reachability returns no, won't any socket i/o fail immediately, too?
  • Adam Eberbach
    Adam Eberbach over 12 years
    Yes, that's how Reachability works but it gives you extras like the ability to receive notifications when reachability changes - interrupts, not polling.
  • Fred Collins
    Fred Collins over 12 years
    Excuse me Adam, but if the network is not used but the device is connected and I check for network status, Reachability tell me I've no connection. This answer explain what I would say in a better way: stackoverflow.com/a/9186073/719127
  • smparkes
    smparkes over 12 years
    Right. I guess my point was for the question at hand, using reachability isn't any better than just trying to make the connection.
  • Adam Eberbach
    Adam Eberbach over 12 years
    Updated with a link to the code sample - checking reachability before making your actual request can be done.
  • Fred Collins
    Fred Collins over 12 years
    Thanks guy, I'll try to implement it in while and I come back with the response. :-)
  • Fred Collins
    Fred Collins over 12 years
    Hi mattt and thanks for you reply. But your suggestion is to check for current status of internet connection before every method that uses internet and if there's no connection displays an alert?
  • mattt
    mattt over 12 years
    No, not at all. AFHTTPClient monitors for reachability changes and executes the specified block when that happens. The block has a single argument, which is a boolean for whether or not the baseURL is reachable.
  • Fred Collins
    Fred Collins over 12 years
    I've subclassed AFHTTPClient and I've overridden -setReachabilityStatusChangeBlock: with an NSLog(@"test") inside but the statement is never executed. Why?
  • mattt
    mattt over 12 years
    @FredCollins Check that you've included the SystemConfiguration framework. If that's not linked to the project, that code won't run.
  • Simon
    Simon about 12 years
    @mattt could you add some sample code so I could see what should I do. Thanks
  • Lance
    Lance about 12 years
    @FredCollins You don't override the method, you call it on your subclass and pass in a block which contains the code you want to run. Make sure you take out your override or it WILL NOT WORK.
  • Avinash
    Avinash about 12 years
    Add #import <SystemConfiguration/SystemConfiguration.h> to the header prefix of the project (Prefix.pch). This is required step after adding SystemConfiguration framework.
  • minovsky
    minovsky over 11 years
    @mattt I have set setReachabilityStatusChangeBlock: before setting up a JSONRequestOperationWithRequest:success:failure, is this the right way to do it? if that's the case, when I get a status of AFNetworkReachabilityStatusNotReachable, how do I cancel the operation, or would the failure block be automatically called when it sees a AFNetworkReachabilityStatusNotReachable?