Location Notifications with UNLocationNotificationTrigger

Learn how to use UNLocationNotificationTrigger to set up location-triggered notifications for your iOS app. By Graham Connolly.

4.9 (7) · 1 Review

Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

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:

  1. Place an order.
  2. Simulate the locations using the debugger.

Now when you arrive at Swifty TakeOut, the app will ask the user to check in:

Notify the kitchen alert

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:

  1. Select the project from the Project navigator.
  2. Click the SwiftyTakeOut app target.
  3. Select the Signing & Capabilities tab.
  4. Click the + Capability tab.
  5. Select Background Modes.
  6. Under the Background Modes section, enable Location updates.

Background Modes - 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.

Local Notification

It means going outside, but on the plus side, you’ll be a couple a steps closer to your daily goal. :]

  1. 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.
  2. Build and run the app on your connected iOS device.
  3. Stop the app in Xcode and then disconnect the USB cable from device.
  4. Walk at least 200 meters away from that location.
  5. Open the app and place an order.
  6. Quit the app by launching the App Switcher and swiping upwards.
  7. Walk toward your chosen location. You should then get the notification as you get close to the location.
Note: Unfortunately, you can’t test your app from a terminated state in Xcode. To test this, you need to:

That’s a wrap!

A Happy Monster to celebrate completing the tutorial

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:

  1. Set up and use Core Location.
  2. Register a geofence for region monitoring.
  3. Enable your app for location updates when the app is in the background.
  4. Notify users of a geofence entry event.
  5. 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!