【问题标题】:ios disallow cellular for the whole appios 不允许整个应用使用蜂窝网络
【发布时间】:2012-11-01 13:37:45
【问题描述】:

您好,我已经阅读了一些帖子,发现我可以使用 Apple 的“可达性”示例来检查当前设备是否在 Wi-Fi 或蜂窝网络上运行,并确定是否可以触发连接。但是,我的应用程序中有很多不同类的 webviews 和 HTTP 调用,所以恐怕我必须在每个将启动连接的方法中调用检查。我想问一下是否有任何方法可以检查网络状态并禁止蜂窝网络上的所有流量?非常感谢。

【问题讨论】:

  • Reachability 可以让你观察连接变化 NSNotification "kReachabilityChangedNotification",从而消除了这个问题。

标签: iphone ios wifi reachability cellular-network


【解决方案1】:

您正在寻找通过 NSNotification 广播的 ReachableViaWiFi 网络状态。您可以像这样在代码中进行设置:

@property (nonatomic, assign) NetworkStatus currentNetStatus;

...

- (void) startListeningForWifi{
            Reachability* hostReach = [Reachability reachabilityWithHostName:@"hostName"];
            [hostReach startNotifier];

            // reachability set up
            // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the
            // method "reachabilityChanged" will be called. 
            [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
}

- (void)reachabilityChanged: (NSNotification* )note{
    Reachability *curReach = [note object];
    self.currentNetStatus = [curReach currentReachabilityStatus];
}

然后在进行网络呼叫之前检查currentNetStatus 很容易。如果这不等于ReachableViaWiFi,那么你就没有在wifi上。

【讨论】:

  • 感谢您的回答,这是解决我的问题的一种方法。但是情况有点复杂,比如说我现在有连接下载文件并且网络状态从wifi变为蜂窝,我可以立即取消连接吗?
  • 您可以按照post取消请求
  • 这能回答你的问题吗?
  • 非常感谢。我还没有尝试过,因为我使用了另一种方法来解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 2015-09-06
  • 2013-02-05
  • 2014-04-22
相关资源
最近更新 更多