Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking 2.0 Reachability

I am trying to determine if the user is connected to the internet by using AFNetworking 2.0 and the "AFNetworkReachabilityManager", but it doesen't seem to work. It's always return that there is a valid internet connection, even though the internet is turned off. This is my code:

 -(BOOL)connected {     __block BOOL reachable;      [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {          switch (status) {             case AFNetworkReachabilityStatusNotReachable:                 NSLog(@"No Internet Connection");                 reachable = NO;                 break;             case AFNetworkReachabilityStatusReachableViaWiFi:                 NSLog(@"WIFI");                  reachable = YES;                 break;             case AFNetworkReachabilityStatusReachableViaWWAN:                 NSLog(@"3G");                 reachable = YES;                 break;             default:                 NSLog(@"Unkown network status");                 reachable = NO;                 break;                  [[AFNetworkReachabilityManager sharedManager] startMonitoring];         }     }];      return reachable;  } 

This method is called from my viewDidLoad method. Is there something wrong with my code, since it isn't working?

like image 389
7c9d6b001a87e497d6b96fbd4c6fdf Avatar asked Nov 04 '13 19:11

7c9d6b001a87e497d6b96fbd4c6fdf


People also ask

What is AFNetworking in iOS?

AFNetworking is an open source networking library for iOS and macOS that simplifies a developer's tasks with a RESTful networking API and creates modular request/response patterns with success, progress, and failure completion blocks. It has a very active developer community and is used in some of the best apps.

What is AFNetworking framework?

AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.


2 Answers

You're making this more difficult than it needs to be. Try this:

- (void)viewDidLoad {    [super viewDidLoad];     [[AFNetworkReachabilityManager sharedManager] startMonitoring];  }  - (BOOL)connected {     return [AFNetworkReachabilityManager sharedManager].reachable; }    

If you also want to be notified when the status changes, then implement setReachabilityStatusChangeBlock

Hope this helps!

like image 138
backofthecup Avatar answered Oct 02 '22 14:10

backofthecup


That's because that block is only executed when reachability changes.

To get the current status, you can do this:

- (BOOL)connected {     return [AFNetworkReachabilityManager sharedManager].reachable; } 
like image 37
Marcelo Fabri Avatar answered Oct 02 '22 14:10

Marcelo Fabri