UILocalNotification 没有做任何事情

UILocalNotification not doing anything

这似乎是一个愚蠢的问题,但这是我第一次使用 UILocalNotification,我无法让它工作以进行快速测试。它只是什么都不做。

1.我在 AppDelegate

中创建了 2 个变量
let today = NSDate()
let notification: UILocalNotification = UILocalNotification()

2。然后在 applicationDidEnterBackground 函数中,我有以下

    notification.fireDate = today.dateByAddingTimeInterval(10)
    notification.alertTitle = "My App Test"
    notification.alertBody = "Testing Notification \n :)"
    UIApplication.sharedApplication().presentLocalNotificationNow(notification)
    UIApplication.sharedApplication().scheduleLocalNotification(notification)

3。还将此添加到 applicationDidBecomeActive 函数

UIApplication.sharedApplication().cancelAllLocalNotifications()

再次阅读文档后,我意识到我错过了关键的第一步,即首先注册我的应用程序以获取用户通知。 Apple 文档是用 OBJ-C 编写的,但我能够弄明白以便将其转换为 swift。这就是我所做的:

1.我将它添加到我的 AppDelegate didFinishLaunchingWithOptions 函数中,它现在可以工作了

var types: UIUserNotificationType = UIUserNotificationType()
types.insert(UIUserNotificationType.Alert)
types.insert(UIUserNotificationType.Badge)

let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)

UIApplication.sharedApplication().registerUserNotificationSettings(settings)