Continuing our look at Notifications in iOS 10, today we'll check out the different notification triggers we can use to display notifications in our app. Let's get started.
We'll use the same standard authorization and testbed setup we did in Bite #258, only this time, we'll create some triggers.
We'll compose a quick
let notification = UNMutableNotificationContent() notification.title = "Entered Mothership!" notification.body = "Welcome to Apple."
Now, we'll start trying out triggers. First, let's look at a location trigger:
let region = CLCircularRegion( center: CLLocationCoordinate2DMake( 37.3278964, -122.0215575 ), radius: 100.0, identifier: "Mothership" ) region.notifyOnExit = false let trigger = UNLocationNotificationTrigger( region: region, repeats: false )
This will cause our notification to be displayed when the user enters the area around Apple's new Spaceship campus. Neat!
Then, we'll hand everything off to the notification center via a
UNNotificationRequest, just as we did before:
UNUserNotificationCenter.current().add( UNNotificationRequest( identifier: "mothership-1", content: notification, trigger: trigger ) )
When it comes to time-based triggers, we're given a couple of options.
We'll compose another quick
let notification = UNMutableNotificationContent() notification.title = "WAKE UP!" notification.body = "You're late for the Mothership!"
UNCalendarNotificationTrigger. This allows us to specify only the components we want to trigger on. For example, here we're creating a trigger that will repeat every morning at 7:15 AM:
let trigger = UNCalendarNotificationTrigger( dateMatching: DateComponents(hour: 7, minute: 15), repeats: true )
We can also easily trigger a notification after a delay. Here we show one after 30 seconds:
let trigger = UNTimeIntervalNotificationTrigger( timeInterval: 30, repeats: false )