Setting up reachability with AFNetworking 2.0

2019-01-21 20:03发布

问题:

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.

回答1:

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.



回答2:

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];

    }

}];


回答3:

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.



回答4:

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)
    }