Monday, September 29, 2014

iOS 8 - Displaying Local Notifications

Displaying local notifications has changed a little in iOS 8. You now need to seek the user's permission in order to display notifications. You can do so via the AppDelegate, like this:

    func application(application: UIApplication
    didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(
                forTypes:
                UIUserNotificationType.Sound |
                UIUserNotificationType.Alert |
                UIUserNotificationType.Badge, categories: nil))
            
        return true

    }


Once user's permission is granted, you would now be able to display a notification as usual:

        var localNotification =  UILocalNotification()
        //---the message to display for the alert---
        localNotification.alertBody =
            "You have entered the region you are monitoring"
        
        //---uses the default sound---
        localNotification.soundName = UILocalNotificationDefaultSoundName
        
        //---title for the button to display---
        localNotification.alertAction = "Details"
        
        //---display the notification---

        UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)

No comments: