I am trying to detect if the user is near or enters my desired location. I am using CLLocationManager
to monitor this action, but for some reason it doesn't work. I am in the current location but didEnterRegion
not called. Here is my code:
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
// Register the region.
let maxDistance = locationManager.maximumRegionMonitoringDistance
let region = CLCircularRegion(center: center,
radius: maxDistance, identifier: "identifier")
region.notifyOnEntry = true
region.notifyOnExit = false
locationManager.startMonitoring(for: region)
}
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region is CLCircularRegion {
print("entered....")
}
}
I also added privacy descriptions in plist file:
How can I fix this issue?
Edited:
requestState(for region:)
and didDetermineState:for:
work now, but how can I check if the user is near or at the location? for example, if the user is near or in the region do something and if not do something else.
Edited 2
let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
let region = CLCircularRegion(center: center, radius: 1000, identifier: "Store")
let controller = LocationController()
controller.requestWhenInUseAuthorization()
controller.requestState(for: region) { (state) in
switch state {
case .inside:
print("inside region")
case .outside:
print("outside region")
case .unknown:
print("unknown")
}
}