Creating local notification not always have to been executed immediately. Sometimes the user needs to be notified in some circumstances like a specific location or time
Swift has four types of triggers for notification. You can create and use three of them and one is reserved for push notification sent from the server.
- TimeInterval (relative time)
- Calendar (absolute time)
If you missed the previous post about creating local notification you can find it here.
The time interval trigger starts counting time after adding it to NotificationCenter and after a specified time it’s executed. It depends on relative time.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3.5, repeats: false)
Notification will show after 3.5 seconds and it’ll be executed only once. You can set repeats to true but then minimal timeInterval has to be 60 seconds.
Calendar trigger depends on absolute time, you can set a specific time when notification will show, for example, every hour 3 minutes and 13 seconds past or every Monday at 3:15. To repeat this set repeats to true.
var dateComponents = DateComponents()
dateComponents.minute = 13
dateComponents.second = 3
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
The notification will show when the user enters or exits a specific location. To set this remember about permission for the location and import CoreLocation.
You need to set a lat/long and radius from this place, the radius is in meters.
let center = CLLocationCoordinate2D(latitude: 51.506, longitude: -0.11)
let region = CLCircularRegion(center: center, radius: 5000.0, identifier: “London”)
region.notifyOnEntry = true
region.notifyOnExit = true
let trigger = UNLocationNotificationTrigger(region: region, repeats: false)
notifyOnEntry and notifyOnExit determinate when the notification should be shown. If you set both on true and repeats on false then the notification will show only once.
The location trigger should work smoothly but sometime there could be some delay in delivery.
UNPushNotificationTrigger is created by Apple when a notification is delivered via APN.
To set trigger to replace nil with trigger variable in notification request.
// identifier and content are created previously
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)