2012-11-13 33 views
0

嗨我已阅读了一些帖子,并看到我可以使用来自Apple的“可达性”示例来检查当前设备是在Wi-Fi或蜂窝网络上运行,并决定是否可以触发连接。然而,在我的应用程序中,我在不同的类中有很多webviews和HTTP调用,所以恐怕我必须在每个将启动连接的方法中调用该检查。我想问问是否有任何方法检查网络的状态并禁止蜂窝上的所有通信?非常感谢。ios不允许蜂窝整个应用程序

+0

Reachability允许您观察连接更改NSNotification“kReachabilityChangedNotification”,从而消除此问题。 –

回答

0

您正在寻找通过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上。

+0

感谢您的回答,它是解决我的问题的一种方法。但情况有点复杂,目前我有一个连接下载一个文件,网络状态从wifi更改为蜂窝,我可以立即取消连接? – user1653545

+0

你取消请求通过下面这个[post](http://stackoverflow.com/questions/11070175/how-to-cancel-network-request-with-afnetworking) – foggzilla

+0

这是否回答你的问题? – foggzilla