Reputation: 729
I want to check if user device is connected to internet or not before make a request to server. For this i'm doing this in AppDelegate
class
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[self connectivity];
}
-(void)connectivity
{
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
}];
// Set the reachabilityManager to actively wait for these events
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
and when i make any request i do
AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
BOOL con = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN);
//BOOL con =[AFNetworkReachabilityManager sharedManager].reachable;//give same result as networkReachabilityStatus
But first time when i make request it gives me NO
and after some time it gives correct value. Please suggest the best way to monitor connectivity.
Upvotes: 1
Views: 770
Reputation: 5076
You can check property networkReachabilityStatus:
AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
BOOL rechable = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN);
If you want to try do smth while the status is AFNetworkReachabilityStatusUnknown, you can use:
BOOL rechable = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusUnknown);
P.S.
Checking of the reachability is asynchronous operation, see SCNetworkReachabilityRef, therefore you can't get networkReachabilityStatus in the applicationDidFinishLaunching method.
Upvotes: 1