我一直在测试不同的方法来实现当应用程序处于后台时知道设备是否恢复互联网的可能性,所以我测试的第一个代码是 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;
}
}
}
我的问题是: 当应用程序处于后台时,当互联网状态发生变化时获得通知的方式是什么?