当应用程序的状态处于非活动状态时,是否可以获取本地通知

时间:2012-02-03 08:31:08

标签: ios uilocalnotification localnotification

我正在开发一个iOS应用程序,我必须得到本地通知,但是在应用程序状态不活动的情况下。当应用程序处于后台状态时,我成功收到通知。 那么,当应用程序处于非活动状态时,是否可以获得本地通知? 或者也许这只能通过使用推送通知来实现?

此致 阿尔钦

3 个答案:

答案 0 :(得分:9)

您需要在应用代理中的两个位置回复本地通知:

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

- (void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification

第一个是针对您的应用未运行的时间 - 使用launchOptions参数检查您的应用是否因本地通知而启动。

第二个用于您的应用当前正在运行的时间(有效或无效)。您可以通过applicationState方法检查NSApplication的application:didReceiveLocalNotification:属性来检查应用是否处于非活动状态。

答案 1 :(得分:2)

- (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;
}

答案 2 :(得分:0)

当然,只需使用列出的willResignActiveNotification通知监听器即可 here