ios - 在后台检测可达性

标签 ios multithreading swift background reachability

我一直在测试不同的方法来实现当应用程序处于后台时了解设备是否恢复互联网的可能性,所以我测试的第一个代码是 Apple 可达性示例代码 http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

但是当应用程序处于后台时,此代码不会通知互联网状态。所以我也尝试了以下代码,当应用程序从后台状态启动到前台时它可以工作(与 Apple 可达性示例代码相同)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


// check for internet connection
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(checkNetworkStatus:)
                                             name:kReachabilityChangedNotification object:nil];

// Set up Reachability
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];

 ...
 }


 - (void)applicationDidEnterBackground:(UIApplication *)application {

// check for internet connection
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(checkNetworkStatus:)
                                             name:kReachabilityChangedNotification object:nil];

// Set up Reachability
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];

}



- (void)checkNetworkStatus:(NSNotification *)notice {
// called after network status changes

NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
    case NotReachable:
    {
        NSLog(@"The internet is down.");
        break;
    }
    case ReachableViaWiFi:
    {
        NSLog(@"The internet is working via WIFI");

        //Alert sound in Background when App have internet again
        UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
        if (notification) {
            [notification setFireDate:[NSDate date]];
            [notification setTimeZone:[NSTimeZone defaultTimeZone]];
            [notification setRepeatInterval:0];
            [notification setSoundName:@"alarmsound.caf"];
            [notification setAlertBody:@"Send notification internet back"];
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }


        break;
    }
    case ReachableViaWWAN:
    {
        NSLog(@"The internet is working via WWAN!");


        //Alert sound in Background when App have internet again
        UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
        if (notification) {
            [notification setFireDate:[NSDate date]];
            [notification setTimeZone:[NSTimeZone defaultTimeZone]];
            [notification setRepeatInterval:0];
            [notification setSoundName:@"alarmsound.caf"];
            [notification setAlertBody:@"Send notification internet back"];
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }

        break;
    }
}
}

我的问题是: 当应用程序处于后台时互联网状态发生变化时,如何获得通知?

最佳答案

Live 如果网络连接发生变化,您将无法更改,最好的您可以做的就是使用 Background Fetch 模式来自 能力。首先,您需要选中背景模式的复选框: enter image description here

然后您需要尽可能多地询问时间间隔,越快越好,所以我建议application:didFinishLaunchingWithOptions:,您需要输入以下行:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    return YES;
}

UIApplicationBackgroundFetchIntervalMinimum 它尽可能频繁,但它不是从文档中获取的确切秒数:

The smallest fetch interval supported by the system.

然后当后台获取将触发时,您可以使用以下方法 checkin AppDelegate:

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    [reachability startNotifier];
    NetworkStatus status = [reachability currentReachabilityStatus];

    switch (status) {
        case NotReachable: {
            NSLog(@"no internet connection");
            break;
        }
        case ReachableViaWiFi: {
            NSLog(@"wifi");
            break;
        }
        case ReachableViaWWAN: {
            NSLog(@"cellurar");
            break;
        }
    }
    completionHandler(YES);
}

所有这些都适用于 iOS 7.0 或更高版本。

关于ios - 在后台检测可达性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670774/

相关文章:

ios - 使用通用协议(protocol)作为接口(interface)

swift - ArrayLiteralConvertible : Just a normal protocol?

c++ - 在正在运行的线程中处理事件

ios - 在 UITableView 中检测点击

ios - 按用户位置距 firebase 的距离对数组进行排序

ios - 将来自服务器的 UTC 日期存储在 NSDate 对象中

java - 为什么我的多线程程序是顺序执行的?

java - 是否可以使用 JUnit 测试多线程?

ios - 仅为一个 tableView 设置行高并忽略 heightForRowAtIndexPath 中的其他 tableView?

ios - 如何从 CBPeripheral 和 CBCenter 获取 Mac 地址