2

How do I know if the device has changed its network? For example with this use case:

  1. User connects to Wi-Fi A.
  2. User starts my app.
  3. User connects to Wi-Fi B. (or even 3G)
  4. User restores app.

Is there anyway to notify the app, that the device changed from Wi-Fi A to Wi-Fi B?

4

4 回答 4

3

Apple 已经很好地为我们创建了一个完整的示例。它被称为可达性(Apple 链接)。这是它的要点:

在 .h 文件中:

// declare Reachability, you no longer have a singleton but manage instances 
Reachability* reachability; 

在 .m 文件中:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil]; 
reachability = [Reachability reachabilityForInternetConnection]; 
[reachability startNotifier]; 
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus]; 
if(remoteHostStatus == NotReachable) 
{
    NSLog(@"no");
} 
else if (remoteHostStatus == ReachableViaWiFiNetwork) 
{
    NSLog(@"wifi"); 
} 
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) 
{
    NSLog(@"cell"); 
} 
..... 

- (void) handleNetworkChange:(NSNotification *)notice 
{   
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];   
    if(remoteHostStatus == NotReachable) 
    {
        NSLog(@"no");
    }   
    else if (remoteHostStatus == ReachableViaWiFiNetwork) 
    {
        NSLog(@"wifi"); 
    }   
    else if (remoteHostStatus == ReachableViaCarrierDataNetwork) 
    {
        NSLog(@"cell"); 
    } 
} 
于 2013-03-13T07:28:31.467 回答
1

这是与 ARC 兼容的一个不错的替代方案 https://github.com/tonymillion/Reachability

于 2013-03-13T08:21:20.183 回答
0

在项目中使用可达性获取网络类型

SCNetworkReachability 接口可以帮助您。基本上,您创建一个所谓的可达性引用,然后在其上调用 SCNetworkReachabilityGetFlags 以获取有关连接的信息。

于 2013-03-13T07:50:39.240 回答
0

正如其他人提到的使用可达性heres链接

于 2013-03-13T08:52:36.953 回答