簡體   English   中英

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中進行了嘗試,但每次啟動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;
            }
        }

如何創建首次本地通知? 如果有人解釋,那就太好了。

在userDefaults中添加標志,然后檢查是否

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

如果沒有,請打開通知方法並在那里

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

您可以這樣使用NSUserDefaults

在您的AppDelegate didFinishLaunchingWithOptions:中:

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")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM