所以,我知道這裏有很多關於實現可達性的帖子,但我找不到任何回答我的具體問題。可達性hostStatus返回false否
我正在實現下面的代碼,但由於某種原因,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");
}
}
}
我的猜測是,它是進入CheckNetworkStatus方法hostStatus連接已被適當的檢查之前。
任何幫助真的很感謝!