Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Local notification on Region Monitoring for Swift

Hi folks, im working on a project where I would like to receive a Local notification when the user enters or exits a region.

So far, only the console prints the NSLogs when i enter or exit. All the code is written within the viewcontroller.

ANY help would be greatly appreciated, Fernando

    @IBAction func regionMonitoring(sender: AnyObject) {
        manager?.requestAlwaysAuthorization()

        let notreDame = CLCircularRegion(center: CLLocationCoordinate2D(latitude: 48.858400, longitude: 2.294500), radius: 200, identifier: "notreDame")
        manager?.startMonitoringForRegion(notreDame)

    }

    func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {

        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge , .Sound], categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)

        let notification = UILocalNotification()
        notification.region = region
        notification.alertBody = "Hello this should popUp" // text that will be displayed in the notification
        NSLog("Entering region")

    }

    func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
        NSLog("Exit region")

I found a video of something similar https://www.youtube.com/watch?v=seB8tpBrzj0

1 Answer

Everything is working as it should. UILocalNotification will only pop to your screen if your app is running in the background. If you want the user to be notified while they are on the app as well, you would need to include an alertController.

let alertController = UIAlertController(title: "In Region", message: "Your in NotreDame!", preferredStyle: .Alert)
        let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(defaultAction)
        presentViewController(alertController, animated: true, completion: nil)