Triggering Location-Based Notifications in iOS: A Quick Guide
Notifications are a powerful tool for user engagement, allowing apps to convey meaningful messages to users. iOS offers two types of notification services: local notifications that are triggered locally and remote notifications or push notifications that are first sent to Apple’s push notification service (APNS) and then forwarded to the user.
Now, let’s take a closer look at how we can trigger a local notification when a user enters or exits a specific location.
Requesting Permissions
Assuming you’ve created an Xcode project, let’s import CoreLocation and UserNotifications to access user’s location and send notification to users. The first part of this guide is to request notification and location permissions from the user.
In the ContentView of you Xcode project add the following code to get permissions from the user.
import SwiftUI
import UserNotifications
import CoreLocation
struct ContentView: View {
let locationManager = CLLocationManager()
var body: some View {
VStack(spacing: 20) {
Button("Request Permission"){
UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .badge, .alert]){(success, error)in
if let error = error {
print("Error: \(error)")
}else {
print("Success")
}
}
locationManager.requestWhenInUseAuthorization()
}
}
}
}
This code creates a button and requests the user for permission to play sound and show badges and alerts while displaying a notification. It also initialises an instance of CLLocationManager, which is used to request access to the user’s location when the app is in use.
Modifying iOS Custom Target Properties
Next, navigate to the project navigator (or use the Command + 1 shortcut), locate and click on your project, then choose your project’s name from the list under the Targets subheading. Proceed to click on the “Info” tab, double-click on any of the target properties displayed in the section labeled “Custom iOS Target Properties,” and finally, select “Add Row”.
Enter “Privacy — Location Always and When In Use Description” under the “Key” column and provide a suitable description such as “We use your location to send you location-based notifications.” This description will be presented to the user when requesting their permission.
Add another row and now enter “Privacy — Location When In Use Description” and enter the same description as above.
With these steps completed, we are now prepared to request location and notification permissions from the user.
Creating a Notification
If you’ve received a notification before, you can easily understand that it essentially has two main parts: the message (referred to as content in terms of iOS) and the reason it appears (known as a trigger in terms of iOS).
In our case, the content can be as simple as “You’ve reached location A” and the trigger happens when the user enter or exits a predefined location or region.
Let’s add a button in the VStack and to provide iOS with the predefined location and content.
Button("Schedule Notification"){
let content = UNMutableNotificationContent()
content.title = "Testing"
content.subtitle = "This is a test notification"
content.sound = UNNotificationSound.default
let locationCoordinates = CLLocationCoordinate2D(latitude: 16.530666, longitude: 80.796936)
let region = CLCircularRegion(center: locationCoordinates, radius: 500, identifier: "VGA RNWY")
region.notifyOnEntry = true
region.notifyOnExit = false
let trigger = UNLocationNotificationTrigger(region: region, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request){(error) in
if let error = error {
//error
}else {
//success
}
}
}
This code creates an instance of UNMutableNotificationContent, which, as Apple describes, is utilised to define the content of a payload for a local notification.
Specify the coordinates that defines the centre of your location using CLLocationCoordinate2D structure.
Use CLCircularRegion to virtually draw a circular boundary to your location, with the measurements in meters. You can further customize the trigger using notifyOnEntry
and notifyOnExit
options, which are self-explanatory.
Now, it’s time to create a trigger using UNLocationNotificationTrigger that takes CLCircularRegion as a parameter.
Add the trigger to the notification centre and you’re all set to receive location based triggers.
Testing in Xcode Simulator
- Run your App in the Simulator and make sure you’ve provided all the appropriate permission to the application.
- Before clicking “Schedule Notification,” make sure that the simulator’s location is set to a location other than the specified region, such as “Apple,” which you can select from the list by going to “Features” > “Location” > “Apple”. This sets the location to Apple headquarters, Cupertino.
- Click “Schedule Notification” and lock the iPhone( command + L shortcut).
- Change the location of the simulator to the pre-defined coordinates, by selecting “Features” > “Location” > “Custom Location” and enter the coordinates.
If you’ve followed all the instructions, you should have received a notification on your simulator’s home screen.