Setting a Geofence

The geofence is a region we register with the location manager. Open LocationProvider.swift and add the highlighted lines at the end of the method locationManager(_:didUpdateLocations:):

 func​ ​locationManager​(_ manager: ​CLLocationManager​,
  didUpdateLocations locations: [​CLLocation​]) {
 
 guard​ ​let​ location = locations.last ​else​ { ​return​ }
 printLog​(​"location: ​​(​location​)​​"​)
 
»let​ region = ​CLCircularRegion​(center: location.coordinate,
» radius: 10,
» identifier: ​"home"​)
» manager.​startMonitoring​(for: region)
 }

We define a region with the location as the center, a radius of 10 meters, and an identifier. The identifier is passed into the code when the app is activated because of a geofence trigger. It can be used to distinguish between the different geofences. We’re using only one geofence in this application, so the identifier isn’t really necessary. Next, we tell the locationManager to monitor that region.

Pro Tip: Use Reasonable Placeholders

images/aside-icons/tip.png

Even though the identifier won’t be used in our app, we should use an identifier that makes sense. We could change the app later to use more than one geofence. Or maybe we’ll want to add a feature later that measures commute time. And even if we don’t need the identifier in the future, it’s still easier to read than a placeholder like foo.

The first part of the geofence is done. Now we need to add the action that is executed when the device enters or exits the region of the geofence. Add the following two methods to LocationProvider:

 func​ ​locationManager​(_ manager: ​CLLocationManager​,
  didEnterRegion region: ​CLRegion​) {
 
 printLog​(​"didEnterRegion: ​​(​​String​(describing: region)​)​​"​)
 }
 
 func​ ​locationManager​(_ manager: ​CLLocationManager​,
  didExitRegion region: ​CLRegion​) {
 
 printLog​(​"didExitRegion: ​​(​​String​(describing: region)​)​​"​)
 }

These methods are declared in the CLLocationManagerDelegate. The location manager calls these methods of its delegate when the device enters or exits a monitored region. For now we print the events to the log. Let’s see if the geofence works.

Build and run the app on the simulator. When the app has loaded, set the geofence by tapping the Set Home button. Then, change the simulated location in Features > Location > Custom Location... and enter 10 for Latitude and 2 for Longitude. In the console in Xcode, you should see a log entry that says the device exited the region with the identifier home. Now we need to store these events for later evaluation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.15.1