【问题标题】:iOS XMPP check connection to the internetiOS XMPP 检查互联网连接
【发布时间】:2015-08-20 07:56:52
【问题描述】:

我正在开发基于 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.");
    });
}

【问题讨论】:

  • 为什么你有一个延迟的调度,然后一个警报。这段代码实际上没有意义。此外,这不是检查该连接的地方,您应该在 ViewController 中进行......
  • 那我该怎么办?我不知道如何实现它?我只是在应用程序运行时尝试检查互联网并当前打印日志。如果互联网不可用..
  • 我假设如果图书馆工作,它正在检查一种互联网形式(我不熟悉这个图书馆,通常使用苹果的示例代码来检查互联网连接)。这个库只检查本地wifi吗?你连接到本地wifi了吗?或者您是否连接到蜂窝网络......或者什么都没有?您是否还在 Safari 中验证了您在没有密码屏幕或其他内容的情况下已连接?您可能想尝试使用 Apple 提供的可达性框架/示例代码来验证您的结果。

标签: ios xmppframework


【解决方案1】:

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

【讨论】:

  • 感谢您的建议。但是这个警告呢?WARNING there have been reports of apps being rejected when Reachability is used in a framework. The only solution to this so far is to rename the class.
  • 完全没问题。该警告适用于那些构建自己的使用此类的框架的人。您可以将其重命名为您想要的任何名称。我的项目使用这个类,并且从未因此而被拒绝。
【解决方案2】:

试试这个代码:

- (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;
}

【讨论】:

  • 谢谢兄弟。有用。我还有一个问题。此代码还检查服务器超时?我已连接到互联网,但服务器没有响应。
  • 你不应该以这样的方式检查互联网连接的可用性!请改用Reachability。
  • 你也可以使用Reachablity 或者Apple in Demo 我建议你从Apple demo 中使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 2017-03-16
  • 2014-02-08
相关资源
最近更新 更多