Swift - 如何创建第一次应用程序启动本地通知?

时间:2016-07-18 11:10:09

标签: ios swift uilocalnotification

我已在 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 中尝试过,但每次启动App时仍会显示通知。

       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;
            }
        }

如何创建首次本地通知?如果有人解释它会很棒。

2 个答案:

答案 0 :(得分:1)

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

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

如果没有,打开通知方法,那里

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

答案 1 :(得分:1)

您可以使用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")
}