我希望在加载View时能够检查Internet连接。预先确定我观点的内容。

我有以下viewDidLoad方法:

- (void)viewDidLoad {
    [super viewDidLoad];

    if(![self hasInternetConnection]){
        NSLog(@"SHOW ORIGINAL DOC");
    }
    else{
        NSLog(@"SHOW NEW DOC");
    }
}

我有一个名为hasInternetConnection的方法,如下所示:
- (BOOL)hasInternetConnection{

    NSLog(@"Starting connection test");

    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

    // Internet is reachable
    internetReachableFoo.reachableBlock = ^(Reachability*reach){
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"We have internet");
            return YES;
        });
    };

    // Internet is not reachable
    internetReachableFoo.unreachableBlock = ^(Reachability*reach){
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"We do not have internet");
            return NO;
        });
    };

    [internetReachableFoo startNotifier];

}

我不想使用以下已弃用的Apple可达性类:
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];

如何更改-(BOOL)hasInternetConnection中的代码,以有效地返回布尔值以使我的方法起作用?

最佳答案

我在我的项目中做什么:

创建类型为NSObject的自定义类CheckInternet
CheckInternet.h文件中

+ (BOOL) isInternetConnectionAvailable;

并在CheckInternet.m文件中
+ (BOOL) isInternetConnectionAvailable
{
Reachability *internet = [Reachability reachabilityWithHostName: @"www.google.com"];
NetworkStatus netStatus = [internet currentReachabilityStatus];
bool netConnection = false;
switch (netStatus)
{
    case NotReachable:
    {
        NSLog(@"Access Not Available");
        netConnection = false;
        break;
    }
    case ReachableViaWWAN:
    {
        netConnection = true;
        break;
    }
    case ReachableViaWiFi:
    {
        netConnection = true;
        break;
    }
}
return netConnection;
}

将该类导入到所需的类中,现在您可以访问

viewDidLoad或您需要的任何其他方法中
if ([CheckInternet isInternetConnectionAvailable])
{
    // internet available
}
else
{
    // no internet
 }

10-08 15:34