Topics

#43: Local Notifications πŸ“

Topics

Local Notifications are a way to display a system notification to a user of your app without needing to implement a push server. You simply schedule them using an NSDate and they are presented at that time. Let's take a look.

Register for Notifications

Since iOS 8, we've had two different things to register for: User Notifications and Remote notifications. Since we'll be β€œsending” Local Notifications, we only need to register for User Notifications.

In didFinishLaunchingWithOptions:

application.registerUserNotificationSettings(
  UIUserNotificationSettings(
    forTypes: [.Alert, .Sound, .Badge], 
    categories: nil
  )
)

This will prompt the user for permission to see notifications, except instead of coming from a backend server, they'll be generated locally on the device.

Schedule a Local Notification

After we get the didRegisterUserNotificationSettings callback, we're ready to schedule a notification. We use the UILocalNotification class to configure all the aspects of how the notification will look and behave:

func landSpaceship() {
  autopilotPerformAction(.LandShip)

  let landingTime = 30.0 // in seconds

  let n = UILocalNotification()

  n.alertTitle = "Spaceship Landed!"
  n.alertBody = "Good news everyone! Our ship has successfully landed."

  n.timeZone = NSCalendar.currentCalendar().timeZone
  n.fireDate = NSDate(timeIntervalSinceNow: landingTime)

  UIApplication.sharedApplication().scheduleLocalNotification(n)
}