所以,我知道这里有很多关于实现可达性的帖子,但我找不到任何可以回答我的具体问题的帖子。
我正在实现以下代码,但由于某种原因,hostStatus 总是以 NotReachable 的形式返回。
我的 .h 文件:
#import <UIKit/UIKit.h>
#import "Reachability.h"
@class Reachability;
@interface ViewController : UIViewController<UINavigationControllerDelegate>{
Reachability* hostReachable;
Reachability* internetReachable;
}
@property (nonatomic, assign) BOOL wifiReachable;
@property (nonatomic, assign) BOOL networkReachable;
@property (nonatomic, assign) BOOL internetUsable;
我的 .m 文件:
#import "ViewController.h"
#import "Reachability.h"
#import "Reachability.m"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachable = [Reachability reachabilityForInternetConnection];
hostReachable = [Reachability reachabilityWithHostName:@"www.google.com"];
[internetReachable startNotifier];
[hostReachable startNotifier];
// now patiently wait for the notification
[self checkNetworkStatus:kReachabilityChangedNotification];
if(self.internetUsable==TRUE){
//DO STUFF
}
else{
[self internetAlert];
//DO OTHER STUFF
}
}
-(void) checkNetworkStatus:(NSNotification *)notice{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
NSLog(@"%u", hostStatus);
if(internetStatus==NotReachable){
NSLog(@"The internet is down.");
self.internetUsable=FALSE;
}
else{
if(internetStatus==ReachableViaWWAN){
NSLog(@"The internet is working via WWAN.");
self.networkReachable=TRUE;
self.internetUsable=TRUE;
}
else if (internetStatus==ReachableViaWiFi) {
NSLog(@"The internet is working via WIFI.");
self.wifiReachable=TRUE;
self.internetUsable=TRUE;
}
else{
self.networkReachable=FALSE;
self.wifiReachable=FALSE;
self.internetUsable=FALSE;
NSLog(@"The internet is NOT useable.");
}
}
if(self.internetUsable==TRUE)
{
if(hostStatus==NotReachable)
{
self.internetUsable=FALSE;
NSLog(@"Could not connect to the host");
}
}
}
我的猜测是它在正确检查 hostStatus 连接之前进入 CheckNetworkStatus 方法。
任何帮助将不胜感激!