我正在开发一个 iOS 应用程序,我必须获得本地通知,但如果应用程序的状态处于非活动状态。当应用程序处于后台状态时,我成功收到通知。那么,当应用程序处于非活动状态时,是否可以获得本地通知?或者也许只有使用推送通知才能做到这一点?
问候, 阿门
我正在开发一个 iOS 应用程序,我必须获得本地通知,但如果应用程序的状态处于非活动状态。当应用程序处于后台状态时,我成功收到通知。那么,当应用程序处于非活动状态时,是否可以获得本地通知?或者也许只有使用推送通知才能做到这一点?
问候, 阿门
您需要在应用委托的两个位置响应本地通知:
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- (void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
第一个是当您的应用程序未运行时 - 使用该launchOptions
参数检查您的应用程序是否由于本地通知而启动。
第二个是您的应用程序当前正在运行的时间(活动或非活动)。applicationState
您可以通过检查方法中的 NSApplication 属性来检查应用程序是否处于非活动状态application:didReceiveLocalNotification:
。
- (void)sendNotification
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// notification.repeatInterval = NSDayCalendarUnit;
localNotification.fireDate = vwPicker.date;
localNotification.alertBody = txtAlarmTitle.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.userInfo = @{@"Title": txtAlarmTitle.text};
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[self handleNotification:notification application:application];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification)
[self handleNotification:localNotification application:application];
return YES;
}
-(void)handleNotification: (UILocalNotification *)notification application:(UIApplication *)application
{
NSString *title = [notification.userInfo objectForKey:@"Title"];
[[[UIAlertView alloc]initWithTitle:@"Smart Alarm" message:title delegate:self cancelButtonTitle:@"Answer the Teaser" otherButtonTitles: nil] show];
application.applicationIconBadgeNumber = 0;
}
当然,只需使用此处willResignActiveNotification
列出的通知侦听器