Swift - 如何创建应用首次启动本地通知?

Swift - How creating first time app launch local notification?

我在 didFinishLaunchingWithOptions

中添加了这些
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
self.createLocalNotification()

然后,调用下面的函数。

func createLocalNotification() {

    let localNotification = UILocalNotification()

    localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
    // localNotification.applicationIconBadgeNumber = 1
    localNotification.soundName = UILocalNotificationDefaultSoundName

    localNotification.userInfo = [
        "id": "not_id0",
        "message": "Check notification"
    ]

    localNotification.alertBody = "Check notification"
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

}

要取消这个通知,我在下面的 didReceiveLocalNotification 中尝试过,但每次应用程序启动时仍然显示通知。

       let app:UIApplication = UIApplication.sharedApplication()
        for oneEvent in app.scheduledLocalNotifications! {
            let notification = oneEvent as UILocalNotification
            let userInfoCurrent = notification.userInfo! as! [String:AnyObject]
            let id = userInfoCurrent["id"]! as! String
            if id == "not_id0" {
                //Cancelling local notification
                app.cancelLocalNotification(notification)
                break;
            }
        }

如何创建第一次本地通知?如果有人解释一下就好了。

在 userDefaults 中添加标志,然后检查是否

NSUserDefaults.standardUserDefaults().boolForKey("notified")

如果没有,打开通知方法并放置

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "notified")

您可以这样使用 NSUserDefaults

didFinishLaunchingWithOptions: 在你的 AppDelegate:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    ...

    if let haveShownFirstRunNotification = NSUserDefaults.standardUserDefaults().boolForKey("haveShownFirstRunNotification") {
        if !haveShownFirstRunNotification {
            createLocalNotification()
        }
    }
    ...
}

createLocalNotification中:

func createLocalNotification() {

    ...

    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "haveShownFirstRunNotification")
}