Search code examples
iosswiftuilocalnotification

Swift - How creating first time app launch local notification?


I have added these in didFinishLaunchingWithOptions

let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
self.createLocalNotification()

And then, calling below function.

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)

}

To cancel this notification, I have tried below in didReceiveLocalNotification But still display notification every App launching.

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

How Can I create first time local notification? If someone explain It would be great.


Solution

  • You could use NSUserDefaults as such:

    In didFinishLaunchingWithOptions: in your AppDelegate:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        ...
    
        if let haveShownFirstRunNotification = NSUserDefaults.standardUserDefaults().boolForKey("haveShownFirstRunNotification") {
            if !haveShownFirstRunNotification {
                createLocalNotification()
            }
        }
        ...
    }
    

    And in createLocalNotification:

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