【问题标题】:ASIHTTPRequest Reachability How toASIHTTPRequest 可达性 如何
【发布时间】:2011-09-19 14:43:18
【问题描述】:

尽管我很喜欢 ASIHTTPRequest,但没有任何地方记录如何使用修改后的 Reachability 类,而且我在 stackoverflow 或任何示例项目上都找不到它。

目前我在这一点上:

Reachability *reach = [Reachability reachabilityWithHostName:@"http://google.com"];
[reach startNotifier];

if ([reach isReachable]) {
    NSLog(@"connection");
}else{
    NSLog(@"no connection");
}

这似乎不起作用。

【问题讨论】:

标签: iphone asihttprequest


【解决方案1】:

您需要为此设置一个通知处理程序:

Reachability *reach = [Reachability reachabilityWithHostName:@"http://google.com"];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(reachabilityChanged:)
                                             name:kReachabilityChangedNotification
                                           object:nil];
[reach startNotifier];

然后,像这样实现处理程序:

- (void) reachabilityChanged:(Reachability *) reach {
    if ([reach isReachable]) {
       NSLog(@"connection");
    } else{
       NSLog(@"no connection");
    }
}

此外,当您不需要知道事情何时发生变化时,请移除自己作为观察者:

[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];

【讨论】:

  • reachabilityChanged 在实际更改可达性时不会被调用。
  • @MaikelS 这可能是因为reach 为零。这样做:Reachability *reach = [[Reachability reachabilityWithHostName:@"google.com"] retain]; 并在 dealloc 或适当的位置添加一个版本
【解决方案2】:
- (void) reachabilityChanged:(NSNotification *)notification
{
    Reachability *localReachability = [notification object]; 


    if ([localReachability isReachable])

    {
        NSLog(@"connection");
    } else{
        NSLog(@"no connection");
    }

}

,请进行这些更改,然后代码会像魅力一样工作:)

【讨论】:

  • 这实际上是正确的处理程序。如果使用 ARC,请添加一个属性以使其保持活动状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多