如何在后台模式下发出本地通知?

时间:2015-06-15 14:05:08

标签: ios objective-c notifications background-process

在后台获取新数据后,如果有的话,我想发出本地通知。我这样做了:

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

    if ([application respondsToSelector:@selector(registerUserNotifitacionSetting:)]) {

        [application registerUserNotifitacionSetting:[UIUserNotificationSettings settingForTypes: UIUserNotificationTypeAlert|UIUserNotificationTypeBadge categories:nil]];
    }
    return YES;
}

- (void) application:(UIApplication *) application performFetchWithCompletionHandler: (void(^) (UIBackgroundFetchResult)) completionHandler {

    [self SendNotification];

    completionHandler(UIBackgroundFetchResultNewData);

}

-(void) SendNotification {    
    UILocalNotification *notification = [[UILocalNotification alloc]init];

    [notification setAlertBody:@"My text"];
    [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:30]];
    [notification setTimeZone:[NSTimeZone defaultTimeZone]];
    notification.category = @"my category";
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

在设置项目中,我设置了后台提取和远程通知。 调试-(void) application:(UIApplication *) application performFetchWithCompletionHandler: (void(^) (UIBackgroundFetchResult)) completionHandler中的日志未显示时。

请告诉我,我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果你能够转换它,那么这将是完美的iOS 8.3 (swift 1.2)

func applicationDidEnterBackground(application: UIApplication) {

let notification: UILocalNotification = UILocalNotification()
    notification.timeZone = NSTimeZone.defaultTimeZone()

    _ = NSDate()
    notification.fireDate = NSDate(timeIntervalSinceNow: (Time in seconds))
    notification.alertBody = "Alert Body"
    notification.alertAction = nil
    UIApplication.sharedApplication().scheduleLocalNotification(notification)
}