ios - 在 XCODE 中检查互联网连接时如何返回 BOOL

标签 ios objective-c iphone xcode reachability

我希望能够在我的 View 加载时检查互联网连接。预先确定我的 View 内容。

我有以下 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 中的代码以有效地返回 bool 值以使我的方法起作用?

最佳答案

我在我的项目中做什么:

创建一个 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
 }

关于ios - 在 XCODE 中检查互联网连接时如何返回 BOOL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28854560/

相关文章:

ios - UIRefreshControl 和 UITableView 的 backgroundVIew

ios - 使用按钮更改 UIAlertView 内容

ios - 滚动时保持 UITableViewCells 的选定状态

objective-c - 如何减少 Objective-C 代码中的代码重复?

C++ 库集成到 iPhone 应用程序

iphone - 钥匙串(keychain) ARC 错误

ios - 当我调用异步发布请求时如何发送正文中的值

ios - 如何从 iOS 上的图像中提取经过透视校正的矩形区域

objective-c - 当用户在 NSAlert 后按 Enter 时未设置 NSIndexSet

ios - 如何在 iOS 7 上读取通话时长和手机状态?