当应用程序进入后台或模拟器锁定时,UILocalNotification不起作用

时间:2017-01-05 12:00:21

标签: ios objective-c uilocalnotification

我制作了一个UILocalNotification Base演示版。 当我的应用程序进入后台或我的模拟器锁定时,它将触发通知。 但任何人都告诉我它不起作用吗?

代码是

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

    NSDate *todayDate = [[NSDate date]dateByAddingTimeInterval:5.0];
    UIApplication  *app = [UIApplication sharedApplication];
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    if(notification)
    {
        notification.fireDate = todayDate;
        notification.timeZone  = [NSTimeZone defaultTimeZone];
        notification.repeatInterval = 0;
        notification.soundName = UILocalNotificationDefaultSoundName;
        notification.alertBody = @"Yor Are Working On Push Notification";
        [app scheduleLocalNotification:notification];

    }
}

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

    UIApplication *app  =[UIApplication sharedApplication];
    NSArray *oldNotification = [app scheduledLocalNotifications];
    if([oldNotification count ] >0)
    {
        [app cancelAllLocalNotifications];
    }
}

我是ios的新人,如果我错了,请告诉我。或者请给我建议的具体答案链接。 谢谢

1 个答案:

答案 0 :(得分:1)

试试这个..

- (void)applicationDidEnterBackground:(UIApplication *)application {
    UIBackgroundTaskIdentifier backgroundTaskIdentifire = [application beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifire];
    }];

    [self scheduleNotification];
}

- (void)scheduleNotification {
    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Title" arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Yor Are Working On Push Notification" arguments:nil];

    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
    UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"notification" content:content trigger:trigger];
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
}