Reputation: 31
I have to send local notification in iOS when user reaches at his nearby destination stored in local data
I have to trigger notification on did enter region method of clLocationManager delegate
it should trigger even if app is killed
I'm monitoring 20 regions near user's last location when user killed the app
like if user enters in monitored region it should automatically through a local notification
func generateSurroundingRegions(currentLocation: CLLocation) {
// Clear previous regions
regions.removeAll()
for i in 1...100 {
// Generate random angle and distance
let angle = Double(arc4random_uniform(360)) * Double.pi / 180
let distance = Double(arc4random_uniform(1000) + 20) // between 200 and 1200 meters
// Calculate the new region's center
let newLatitude = currentLocation.coordinate.latitude + (distance / 111000) * cos(angle)
let newLongitude = currentLocation.coordinate.longitude + (distance / (111000 * cos(currentLocation.coordinate.latitude * Double.pi / 180))) * sin(angle)
let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: newLatitude, longitude: newLongitude), radius: 50, identifier: "Region\(i)")
regions.append(region)
}
}
func updateMonitoredRegions(currentLocation: CLLocation) {
let sortedRegions = regions.sorted {
let location1 = CLLocation(latitude: $0.center.latitude, longitude: $0.center.longitude)
let location2 = CLLocation(latitude: $1.center.latitude, longitude: $1.center.longitude)
return currentLocation.distance(from: location1) < currentLocation.distance(from: location2)
}
let closestRegions = Array(sortedRegions.prefix(20))
let newMonitoredRegions = Set(closestRegions)
for region in monitoredRegions.subtracting(newMonitoredRegions) {
locationManager.stopMonitoring(for: region)
}
for region in newMonitoredRegions.subtracting(monitoredRegions) {
region.notifyOnEntry = true
region.notifyOnExit = true
locationManager.startMonitoring(for: region)
}
monitoredRegions = newMonitoredRegions
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let currentLocation = locations.last else { return }
lastLocation = currentLocation
generateSurroundingRegions(currentLocation: currentLocation)
updateMonitoredRegions(currentLocation: currentLocation)
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
sendNotification()
print("Entered region: \(region.identifier)")
}
Upvotes: 0
Views: 50