Skip to content

Instantly share code, notes, and snippets.

@ajayjapan
Last active November 28, 2018 09:23
Show Gist options
  • Save ajayjapan/f484c35d78198da13f726c35a4fa3a17 to your computer and use it in GitHub Desktop.
Save ajayjapan/f484c35d78198da13f726c35a4fa3a17 to your computer and use it in GitHub Desktop.
Here App Region Monitoring and Notification Trigger Logic
// MARK: - Significant location change montioring logic
// Called at launch of application if permission is already granted
func startMonitoringSignificantLocationChanges() {
locationManager.startMonitoringSignificantLocationChanges()
}
// Called by location manager if there is a significant location change
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
guard let latestLocation = locations.last else {
// No location found
return
}
self.latestLocation = latestLocation
self.updateTrackedPlaces(coordinate: latestLocation.coordinate)
}
func updateTrackedPlaces(coordinate: CLLocationCoordinate2D) {
// Fetches new places
dataStore.retrievePlaces(latitude: coordinate.latitude, longitude: coordinate.longitude) { [unowned self] (success, data, count) in
if self.authorized {
// Track the new places
self.trackPlaces(places: data)
}
}
}
func trackPlaces(places: [Place]) {
// Removes all the currently monitored regions
self.removeAllMonitoredRegions()
// Saves the new places in our place data store
PlaceManager.shared.savePlaces(places: places)
for place in places {
// Starts monitoring the new places
self.locationManager.startMonitoring(for: place.region())
}
}
// MARK: - Region montioring logic
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
guard let region = region as? CLCircularRegion else {
// region type was not valid
return
}
enteredRegion(region)
}
func enteredRegion(_ region: CLCircularRegion) {
if !canTriggerNotification(for: region) {
return
}
let identifier = region.identifier
// Retrieve place from data store
guard let place = PlaceManager.shared.placeForIdentifier(identifier) else {
// Could not find place with that identifier
return
}
triggerNotificationForPlace(place)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment