Setting up reachability with AFNetworking 2.0
Asked Answered
A

4

17

I am trying to setup Reachability using the new 2.0 AFNetworking.

In my AppDelegate I initialise the sharedManager.

// Instantiate Shared Manager
[AFNetworkReachabilityManager sharedManager];

Then in the relevant VC method I check to see if isReachable:

// Double check with logging
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
    NSLog(@"IS REACHABILE");
} else {
    NSLog(@"NOT REACHABLE");
}

At present this is not working as expected in the simulator, but I imagine this would need to be tested on device and not simulator.

Question What I would like to do is monitor the connectivity within the VC. So I run the following in the viewDidLoad:

// Start monitoring the internet connection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];

How would I then register for the changes? What is/would be called once the network connection changes I cannot see this from the documentation.

Apportionment answered 17/11, 2013 at 20:41 Comment(3)
just fyi, you can remove the code in your AppDelegate, where you say you instantiate the sharedManager. SharedManager is a Singleton object so you can just use it directly. The first time you actually use the manager to do anything relating to network status (isReachable, startMonitoring, setReachabilityStatusChangeBlock), the Singleton will return either a new or the exact same instance. Instantiating it ahead of time, like you're doing, doesn't really do anything useful.Headon
@Headon - You are correct, thanks for that spot.Apportionment
Can i use AFNetworking library for swift ?Sussman
E
44

As you can read in the AFNetworking read me page

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

Here's also a link to the official documentation.

Ers answered 17/11, 2013 at 20:48 Comment(3)
So if startMonitoring is not called, this block is not run. I would simply add this block to viewDidLoad of the VC under the startMonitoring for example?Apportionment
yes that will do. startMonitoring will start the monitoring of the reachability status (duh!) and the block will be called whenever it changes.Ers
Thanks I gathered that was what startMonitoring meant, it was more of a question in regards to the block and where it should be called.Apportionment
L
3

I have a singleton AFHTTPRequestOperationManager class. In the singleton has a method:

+(void)connectedCompletionBlock:(void(^)(BOOL connected))block {

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

    BOOL con = NO;
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

    if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {

        con = YES;
    }

    if (block) {
        [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
        block(con);
    }

}];

}

Before make a request you call this method that return a block indicating if internet is reachable:

[TLPRequestManager connectedCompletionBlock:^(BOOL connected) {
    if (connected) {

       // Make a request

    }else{

        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Notice" message:@"Internet is not available." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];

        [alertView show];

    }

}];
Lopeared answered 18/8, 2015 at 3:15 Comment(0)
M
1

I was just going through your question and all the answers. After that I decided to do all these things once. So, in my existing project I just included the AFNetworking through cocoa-pods and here is the solution which is woking for me completely.

Solution -- First of all AFNetworkReachabilityManager is a singleton class. You don't need to do AppDelegate initialisation for sharedManager.

//[AFNetworkReachabilityManager sharedManager];

#import <AFNetworkReachabilityManager.h>

- (void)viewDidLoad {

//Starting the network monitoring process

[[AFNetworkReachabilityManager sharedManager]startMonitoring];

//Checking the Internet connection...

[[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
    if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {

        UIAlertView *alertNetFound = [[UIAlertView alloc]initWithTitle:@"Network Found" message:@"Please Wait Until It is loading" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertNetFound show];

    }else{
        UIAlertView *alertNetNotFound = [[UIAlertView alloc]initWithTitle:@"No Internet" message:@"Please Check Your Internet Connection Honey" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertNetNotFound show];
    }
}];

So, in this case every time the device connects to a network, it will do the startMonitoring process first and after that it will hit the status block every time and will display alert according to the status.

You can do anything according to your choice by replacing the alerts on the status block. I used this to load an webpage automatically from local storage but I removed that code for simplicity.

Its even working with my simulator and Mac mini..

Thanks

Hope this helped.

Marhtamari answered 6/10, 2015 at 5:13 Comment(0)
C
1

I use this in the app delegate ->

 func reachablityCode() {
        AFNetworkReachabilityManager.sharedManager()
        AFNetworkReachabilityManager.sharedManager().startMonitoring()
        AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock({(status) in
            let defaults = NSUserDefaults.standardUserDefaults()
            if status == .NotReachable {
                defaults.setBool(false, forKey:REACHABLE_KEY)
            }
            else {
                defaults.setBool(false, forKey: REACHABLE_KEY)
            }
            defaults.synchronize()
        })
    }

And then this in the base file ->

 func isReachable() -> Bool {
        return NSUserDefaults.standardUserDefaults().boolForKey(REACHABLE_KEY)
    }
Caladium answered 19/9, 2016 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.