【问题标题】:How to force checking internet reachability using Reachability.m/.h如何使用 Reachability.m/.h 强制检查互联网可达性
【发布时间】:2015-09-09 09:00:45
【问题描述】:

我正在使用 Reachability.m/.h 来检查互联网/wifi 状态。图书馆的一切都很好,每次状态改变时我都会收到通知,这要归功于通知者和观察者,但有时(很少但仍然有时)状态不会改变。

在我的代码的某些部分,我需要“强制”检查可达性。有什么办法可以用 Reachability.m/.h 类做到这一点?

【问题讨论】:

  • 检查我的回答,如果它帮助你不要忘记接受它,如果需要更多澄清,请告诉我,祝你好运
  • 如果您想尝试 Swift 原生版本的 Reachability,您可以查看 github.com/ashleymills/Reachability.swift - 这可能更适合您。

标签: ios iphone swift reachability network-connection


【解决方案1】:

创建一个名为connected的方法:

- (BOOL)connected
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return networkStatus != NotReachable;
}

当你想强制检查可达性时,像这样使用它:

if (![self connected]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No connection" message:@"you have to be connected in order to continue" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alert show];
        NSLog(@"no connection");
    } else {
// the user is connected , write your code here
}

【讨论】:

  • 您的解决方案看起来不错,但它不起作用。当我进行测试时: if(! [self connected]) 即使我没有网络连接,我也可以输入“if”......因此,例如,我可以输入“if”,而我将有 Parse类似的错误:错误:错误域=NSURLErrorDomain 代码=-1009“Internet 连接似乎处于脱机状态。”
  • 你可以使用这样的方法来处理它: - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"connection didFailWithError"); if(error.code==-1009){ // 向用户显示警报,告诉他连接到互联网 } }
  • 我这样做了,但即使出现 -1009 错误,我也从未输入过“didFailWithError”方法。我应该在 info.plist 中添加一些东西吗?还是我必须初始化一些东西?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
相关资源
最近更新 更多