【问题标题】:Setting up Reachability to monitor connectivity and show an Alert设置可达性以监控连接并显示警报
【发布时间】:2013-03-11 18:58:29
【问题描述】:

我想要实现的是监控任何互联网连接吗?所以手机需要主动连接到互联网。如果它确实显示了一个带有重试选项的 UIAlertView(再次尝试连接以查看它是否已更改)。

我正在尝试使用可达性和与 api.parse.com 链接的连接。

在我的 AppDelegate 中,我这样调用 Reachability 的设置:

// Use Reachability to monitor connectivity
[self monitorReachability];

monitorReachability 设置如下:

- (void)monitorReachability {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:ReachabilityChangedNotification object:nil];

self.hostReach = [Reachability reachabilityWithHostName: @"api.parse.com"];
[self.hostReach startNotifier];

self.internetReach = [Reachability reachabilityForInternetConnection];
[self.internetReach startNotifier];

self.wifiReach = [Reachability reachabilityForLocalWiFi];
[self.wifiReach startNotifier];

}

我也有如下可达性改变方法: 编辑 - 更新方法

- (void)reachabilityChanged:(NSNotification* )note {
Reachability *curReach = (Reachability *)[note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
NSLog(@"Reachability changed: %@", curReach);
networkStatus = [curReach currentReachabilityStatus];

if (networkStatus == NotReachable) {
    NSLog(@"NOT REACHABLE");
    return;
} else {
    NSLog(@"REACHABLE");
}

我想了解的是回复。从上面看起来我有一个指向当前状态的指针,我不知道如何使用它。基本上我想要一个 if 语句来检查该链接是否可以通过 Internet 连接访问,如果不是,我可以通过 AlertView。然后,我可以设置一个布尔值供 UIAlertView 使用,即显示ConnectionAlert,然后可以在连接更改和拾取时将其关闭。我也不确定该放在哪里。

【问题讨论】:

    标签: ios ios5 uialertview reachability


    【解决方案1】:

    使用 Reachability 类的最简单方法之一是将 Reachability.h 导入您的 rootViewController 或任何需要连接的地方,然后只需运行此代码...

     Reachability *reach = [Reachability reachabilityForInternetConnection];
    
     NetworkStatus netStatus = [reach currentReachabilityStatus];    
     if (netStatus == NotReachable) {        
     NSLog(@"No internet connection!");   
    //Alert View in here      
    } 
    else {        
    //Do something in here with the connecion e.g:
    
    [self performSelector:@selector(startNSURLRequest) withObject:nil afterDelay:30.0];
    
    }        
    

    这应该会稍微简化一下流程。让我知道您的进展情况。 T

    【讨论】:

    • 我在我的问题中添加了一个编辑。您可以看到我检查了 NotReachable 的 networkStatus。这是否意味着我正在检查 Internet 连接或主机连接?在我的问题的第一种方法中,我为主机和 Internet 连接设置了一个通知程序。这是否只是意味着每次可达性的变化,尽管是互联网连接或主机,都会调用第二种方法??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多