互联网在iOS上可用时的通知

时间:2013-11-01 18:58:53

标签: ios iphone nsurlconnection reachability

当互联网成为可能时,是否有可能在我的应用内收到通知或内容。我知道可达性和各种东西。但我想要的是当互联网在设备上可用时启动一些待定的NSUrlConnections。有没有一种简单的方法可以做到这一点,因为我不想使用循环线程来不断检查可达性。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

好的,这里有关于可达性的非常好的帖子:http://www.mikeash.com/pyblog/friday-qa-2013-06-14-reachability.html(请查看以下评论​​!)
Tldr:您可以在连接恢复时触发阻止,但此解决方案并不完美。没有100%可靠的方法来做到这一点(尝试循环除外),但你可以尝试混合这些方法。

编辑:评论@ Jonah.at.GoDaddy回答:
可达性可以为您提供连接通知错误:误报和误报(您可以在WWDC 2011会话中查看,我不记得哪一个;有两个关于网络)。所以,我的观点是:你永远不应该只依赖那些通知。您可以触发刷新状态更改,但应该有另一种方法(用户交互或某种活动等待)。

答案 1 :(得分:0)

以下是我使用的一些代码......它可能比您需要的更多:

-(void)checkNetworkStatus
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    // check if a pathway to a random host exists
    self.hostReachable = [Reachability reachabilityWithHostname:@"google.com"];
    [self.hostReachable startNotifier];
}


-(void) checkNetworkStatus:(NSNotification *)notice
{
    NetworkStatus hostStatus = [self.hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            DDLogInfo(@"A gateway to the host server is down.");
            if( self.canReachGoogle )
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle: LOCALIZED_NoInternetConnection
                                                            message: LOCALIZED_ConnectionNeeded
                                                           delegate:self cancelButtonTitle:LOCALIZED_Ok otherButtonTitles:nil];
                [alert show];
            }
            self.canReachGoogle = NO;
            break;
        }
        case ReachableViaWiFi:
        {
            DDLogInfo(@"A gateway to the host server is working via WIFI.");
            self.canReachGoogle = YES;

            break;
        }
        case ReachableViaWWAN:
        {
            DDLogInfo(@"A gateway to the host server is working via WWAN.");
            self.canReachGoogle = YES;

            break;
        }
    }
    DDLogInfo(@"Network connection has changed and is now: %@", self.canReachGoogle ? @"enabled" : @"disabled" );
}