Location Notifications with UNLocationNotificationTrigger
Learn how to use UNLocationNotificationTrigger to set up location-triggered notifications for your iOS app. By Graham Connolly.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Location Notifications with UNLocationNotificationTrigger
30 mins
- Getting Started
- What Is Core Location?
- Setting Up Core Location
- Creating a Geofence
- Placing an Order
- Monitoring User Location
- Location Authorization
- Requesting Location Authorization
- Triggering a Location Notification on Arrival
- Notification Authorization
- Using UNLocationNotificationTrigger to Notify the User
- Handling Notification Action
- Simulating User Movement
- Connecting to a physical device
- Simulating the Journey
- Handling a Geofence Entry Event
- Alerting the Kitchen
- Getting Background Updates
- Where to Go From Here?
Alerting the Kitchen
Open LocationManager.swift and add the following beneath storeRegion
at the top of the class:
@Published var didArriveAtTakeout = false
When didArriveAtTakeout
changes, then all the views referencing it get notified and can execute code in response. In your app, when this value changes to true
, the user will see an alert.
Next, still in LocationManager.swift, update both userNotificationCenter(_:didReceive:withCompletionHandler:)
and userNotificationCenter(_:willPresent:withCompletionHandler:)
with the following code, added above the completionHandler()
call in each method:
didArriveAtTakeout = true
Here, you’re updating the value because you’ve arrived at your destination.
Now, you’re going to show an alert when this value changes. To do this, open ContentView.swift and add an alert
modifier in body
after .navigationViewStyle(StackNavigationViewStyle())
:
.alert(isPresented: $locationManager.didArriveAtTakeout) {
Alert(
title: Text("Check In"),
message:
Text("""
You have arrived to collect your order.
Do you want to check in?
"""),
primaryButton: .default(Text("Yes")),
secondaryButton: .default(Text("No"))
)
}
This alert gets executed any time didArriveAtTakeout
changes to `true`.
Build and run the app on your connected iOS device and test this out:
- Place an order.
- Simulate the locations using the debugger.
Now when you arrive at Swifty TakeOut, the app will ask the user to check in:
Next, try putting the app into the background after placing an order, then simulate locations.
You’ll first see a banner notification that says your food will be ready shortly. When you tap that banner, the app will launch. You’ll then see the alert that allows you to Check In.
Wow! Congrats! Your app has come a long way. Users of your app are now notified when they arrive to collect their order, allowing them to get curbside pickup.
But wait, there’s a small issue you have to resolve: If your app is in a suspended or terminated state, your user won’t be notified to check in. In this next section, you’ll fix this issue.
Getting Background Updates
To fix this, changing the permission to Always isn’t the answer, for privacy reasons mentioned in an earlier section. Instead, enter Background Modes, which allows you to continue to use the When in Use authorization.
To enable this:
- Select the project from the Project navigator.
- Click the SwiftyTakeOut app target.
- Select the Signing & Capabilities tab.
- Click the + Capability tab.
- Select Background Modes.
- Under the Background Modes section, enable Location updates.
Next, open LocationManager.swift and add the following code in makeLocationManager()
above the return manager
statement:
manager.allowsBackgroundLocationUpdates = true
This code allows your app to receive location updates when it’s in a suspended state. This state occurs when the app is in the background for some time and no longer able to execute code. With this enabled, your app gets notified when the device enters the geofence, waking it up to handle any events.
It means going outside, but on the plus side, you’ll be a couple a steps closer to your daily goal. :]
- Pick a nearby location as your test region. Apple Maps or Google Maps will give you the longitude and latitude you need for the
location
property. - Build and run the app on your connected iOS device.
- Stop the app in Xcode and then disconnect the USB cable from device.
- Walk at least 200 meters away from that location.
- Open the app and place an order.
- Quit the app by launching the App Switcher and swiping upwards.
- Walk toward your chosen location. You should then get the notification as you get close to the location.
- Pick a nearby location as your test region. Apple Maps or Google Maps will give you the longitude and latitude you need for the
location
property. - Build and run the app on your connected iOS device.
- Stop the app in Xcode and then disconnect the USB cable from device.
- Walk at least 200 meters away from that location.
- Open the app and place an order.
- Quit the app by launching the App Switcher and swiping upwards.
- Walk toward your chosen location. You should then get the notification as you get close to the location.
It means going outside, but on the plus side, you’ll be a couple a steps closer to your daily goal. :]
That’s a wrap!
Where to Go From Here?
Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.
Congratulations! You’ve completed this tutorial and can successfully notify users when they arrive at Swifty TakeOut.
In this tutorial, you learned how to:
- Set up and use Core Location.
- Register a geofence for region monitoring.
- Enable your app for location updates when the app is in the background.
- Notify users of a geofence entry event.
- Request user location permissions and set the message text.
In addition, you learned why you shouldn’t ask for the Always location permission if you don’t need it.
If you’re interested in learning more about geofencing, read more by checking out our Geofencing with Core Location tutorial and Apple’s documentation on geofencing.
Finally, if you’d like to learn more about handling location updates in the background, check out Apple’s Handling Location Events in the Background article.
We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!