2016-04-28 87 views
1

我已经实施了本地通知以检查电池状态。如果电池电量下降1%,则会收到本地通知。这适用于iOS版本低于9的iOS应用程序在前台或后台。 当我将设备操作系统更新到iOS 9时,我在前台收到本地通知,但是无法在应用程序的后台收到通知。 以下是用于实现的代码。当应用程序处于后台模式时电池电量通知不起作用

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

// Enable monitoring of battery status 

**[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];** 

// Request to be notified when battery charge or state changes 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBatteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBatteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil]; 
} 

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

     // Request to be notified when battery charge or state changes 

    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 

    **[[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceBatteryLevelDidChangeNotification object:nil userInfo:nil];** 

    **[[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceBatteryStateDidChangeNotification object:nil userInfo:nil];** 

} 

- (void)checkBatteryStatus 
{ 
    notifyAlarm = [[UILocalNotification alloc] init]; 

    notifyAlarm.alertBody = @“battery alert"; 
    notifyAlarm.soundName = UILocalNotificationDefaultSoundName; 
    [[UIApplication sharedApplication] presentLocalNotificationNow:notifyAlarm]; 
    [self displayNotification]; 
} 

displayNotification方法我们显示通知。

我还启用了应用程序的背景模式,即在屏幕截图中显示。

enter image description here

任何帮助,将不胜感激。提前致谢。

回答

0

您已启用后台获取模式,这意味着您的应用可以接收远程通知并在后台执行网络请求。

不使用可疑和App Store可拒绝的方法,不可能做你想做的事。除非您有一个经过批准的用例,否则Apple特别不希望您能够在后台运行您的应用程序。

相关问题