iOS XMPP 检查互联网连接

iOS XMPP check connection to the internet

我正在开发基于 XMPP 的应用程序。我想设置用户的设备未连接到互联网并且他们尝试登录应用程序,然后 alertview 将显示 you are not connected to internet。我试过了,但没有成功。 这是我的尝试。我应该修改什么?

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

if (![self connect])
{
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.0 * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){



        NSLog(@"not connected.");
    });
}

试试这个代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Check internet connectivity
    if(![self connectedToInternet])
    {
        UIAlertView *uiAlertView = [[UIAlertView alloc]
                                    initWithTitle:NSLocalizedString(@"Connection Error", @"Connection Error")
                                    message:@"you are not connected to internet"
                                    delegate:nil
                                    cancelButtonTitle:NSLocalizedString(@"Ok", @"Ok")
                                    otherButtonTitles:nil];
        [uiAlertView show];
    }else
    {   //internet connection was connected
    }
    return YES;
}

- (BOOL)connectedToInternet
{
    NSURL *url=[NSURL URLWithString:@"http://www.google.com"];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"HEAD"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL];

    return ([response statusCode]==200)?YES:NO;
}

通过执行 HEAD 请求来检查互联网连接是一种非常糟糕的方式来做你想做的事。您的用户可能需要等待大约 60 秒(http 请求的默认超时时间)才能确定他没有互联网连接!这绝对不是用户等待你的产品表现的样子! 有一种确定互联网连接可用性的最佳方法 - 这是一个 Reachability monitoring functions. There is a nice block-based wrapper,我强烈建议您查看。