我想在向服务器发出请求之前检查用户设备是否已连接到互联网。为此我在AppDelegate
类
- (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];
}
当我提出任何要求时
AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
BOOL con = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN);
//BOOL con =[AFNetworkReachabilityManager sharedManager].reachable;//give same result as networkReachabilityStatus
但是,当我第一次发出请求时,它会给我NO
并在一段时间后给出正确的值。请建议监控连接的最佳方法。
答案 0 :(得分:1)
您可以查看属性 networkReachabilityStatus :
AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
BOOL rechable = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN);
如果您想在状态 AFNetworkReachabilityStatusUnknown 时尝试执行smth,您可以使用:
BOOL rechable = (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusUnknown);
P.S。
检查可达性是异步操作,请参阅SCNetworkReachabilityRef,因此您无法在 applicationDidFinishLaunching 方法中获取networkReachabilityStatus。