我修改了apple的可达性类,用于我的服务器ip。但是,当我使用reachabilityWithAddress
时,在app启动时,它不会被称为reachabilityChanged
。它被称为只有互联网连接状态改变。 (比如打开wi-fi)但是,如果我使用reachabilityWithHostName
,则在应用启动时调用reachabilityChanged
函数。
我错过了什么?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
///////////////////////////////////////////////////////////////////////////////////
// Reachability Local Notifications
///////////////////////////////////////////////////////////////////////////////////
hasInternetConnection = NO;
struct sockaddr_in address;
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
address.sin_port = htons(80);
address.sin_addr.s_addr = inet_addr("X.X.X.X");
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name:kReachabilityChangedNotification object: nil];
hostReach = [Reachability reachabilityWithAddress:&address];
[hostReach startNotifier];
...
}
然后在方法中:
-(void)reachabilityChanged:(NSNotification*)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
if ( curReach == hostReach ) {
NetworkStatus netStatus = [curReach currentReachabilityStatus];
if ( netStatus != ReachableViaWiFi && netStatus != ReachableViaWWAN ) {
hasInternetConnection = NO;
}
else {
hasInternetConnection = YES;
}
}
else {
DLog(@"Something go wrong!");
}
}
答案 0 :(得分:2)
使用 reachabilityWithHostName:选择器时,在初始化可达性b / c后很快就会收到通知,在解析该名称之前,主机名的可访问性是未知的。对于 reachabilityWithAddress:,可访问性状态已知,因此无需更改报告。
我通过将以下三行添加到 reachabilityWithAddress:函数中最内部的“if”块来解决问题。
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(reachability, &flags);
ReachabilityCallback(reachability, flags, retVal);
如果可达性实际发生了变化,则会调用相同的回调函数。因此,如果您完全依赖通知,就像我一样,这将导致通知在初始化可达性后发布。