我希望能够在我的 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/