AFNetworking - Check reachability for a domain

元气小坏坏 提交于 2019-12-13 19:27:40

问题


I am using AFNetworking 2.2.1 and trying to use the AFNetworkReachabilityManager to check if a certain domain is reachable, but it always return NO. Maybe I am not using this correctly and would appreciate any pointers.

AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager managerForDomain:@"www.google.com"];
// always returns NO:
NSLog([manager isReachable] ? @"YES" : @"NO");

I also tried with the startMonitoring method (after the manager variable declaration), but with no luck:

[manager startMonitoring];

EDIT: As David pointed out, needed to add a status change block to get notified:

AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager managerForDomain:@"www.google.com"];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
        case AFNetworkReachabilityStatusNotReachable:
            NSLog(@"Never called");
            break;
        default:
            NSLog(@"Never called");
        break;
    }
}];
[manager startMonitoring];
// always returns NO:
NSLog([manager isReachable] ? @"YES" : @"NO");

回答1:


AFReachabilityManager does it's magic asynchronously, so the results of isReachable aren't valid until it's completed. The easiest way to be notified when the result of isReachable is valid is to use setReachabilityStatusChangeBlock: to set a status changed block, and do whatever is appropriate when the status is no longer AFNetworkReachabilityStatusUnknown



来源:https://stackoverflow.com/questions/23525855/afnetworking-check-reachability-for-a-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!