Haris Haris - 1 year ago 103
Swift Question

How to implement geofence triggered local notifications?

I've created a simple geofence based application to monitor the movement of people entering and exiting a geofence and I'm trying to send a notification on these events but can't seem to implement it correctly.

I would really appreciate some explained sample code which would go in the view controller and app delegate.

P.s My knowledge of swift is somewhat limited but I understand most aspects necessary for this application.
Thanks for any help!


This is my function for creating the notification which I think is correct.

func scheduleNotification() {
let centre = CLLocationCoordinate2DMake(51.364730, -0.189986)
let region = CLCircularRegion(center: centre, radius: 150, identifier: "SGS")
region.notifyOnEntry = true

let trigger = UNLocationNotificationTrigger(region: region, repeats: true)

let enterContent = UNMutableNotificationContent()
enterContent.title = "Enter"
enterContent.body = "Entered premesis"
enterContent.sound = UNNotificationSound.default()

let enterRequest = UNNotificationRequest(identifier: "enterNotification", content: enterContent, trigger: trigger)


UNUserNotificationCenter.current().add(enterRequest) {(error) in
if let error = error {
print("Error: \(error)")

I added this to the didFinishLaunchingWithOptions:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {(accepted, error) in
if !accepted {
print("Notification access denied.")

I know I need to call the function but I don't know where to do it so that it is called when the geofence is left. Also I'm not sure how to call it from the view controller as it is in the AppDelegate.

Sorry if I'm being stupid but thanks for the help!

Answer Source

You need to implement the location manager's didEnterRegion and didExitRegion delegate methods. Within your implementation of those methods is where you'll post the local notifications.

If you've already done that, make sure that the app has the proper capibility for posting notifications, and that you've registered the proper notification settings for the app in the app delegate.

Ray Wenderlich has a good tutorial on Geofencing and here's Apple's guide on local and remote push notifications.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download