您好,每当用户在我的应用程序中获得网络连接时,我都想捕获为此我添加了 apples Reachability 类,下面是我在我的 appDelegate 类 didFinishLaunchingWithOptions 方法中使用的片段,
Reachability* reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
我的 reachabilityChanged 选择器方法如下所示
- (void)reachabilityChanged:(NSNotification*)notification
{
Reachability* reachability = notification.object;
if(reachability.currentReachabilityStatus == NotReachable)
NSLog(@"Internet off");
else
NSLog(@"Internet on");
}
但在这里,当我关闭飞行模式和在我的手机中获得网络连接时,我没有收到任何类型的通知。
我错过了什么吗?
最佳答案
我在 appdelegate 中使用变量将当前网络状态存储为 bool
@property (nonatomic, assign) BOOL hasInet;
.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setUpRechability];
}
-(void)setUpRechability
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if (remoteHostStatus == NotReachable) {NSLog(@"no"); self.hasInet-=NO; }
else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"wifi"); self.hasInet-=YES; }
else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"cell"); self.hasInet-=YES; }
}
- (void) handleNetworkChange:(NSNotification *)notice
{
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if (remoteHostStatus == NotReachable) {NSLog(@"no"); self.hasInet-=NO; }
else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"wifi"); self.hasInet-=YES; }
else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"cell"); self.hasInet-=YES; }
// if (self.hasInet) {
// UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Net avail" message:@"" delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil];
// [alert show];
// }
}
关于ios - 如何从 iOS Reachability Class 获取网络连接通知的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17804830/