应用未运行时的本地通知

时间:2015-01-01 17:02:05

标签: swift notifications uilocalnotification

是否可以显示来自应用的某种本地通知,即使该应用未运行(也不在后台)?

例如每日提醒或类似的事情。我知道推送通知是可行的,但它不适合我的应用。

2 个答案:

答案 0 :(得分:16)

您可以轻松安排本地通知,无论应用的状态如何,都会在预定的日期和时间显示这些通知。

首先,您需要获得用户的许可才能提供通知,例如:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound|UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
    return true
}

然后您创建如下通知:

var localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "This is"
localNotification.alertBody = "A notification"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 15)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

查看Local and Remote Notification Programming Guide

答案 1 :(得分:0)

在AppDelegate中,改为使用此功能

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
    application.registerUserNotificationSettings(settings)
    return true;
}