Swift 4 locationManager didEnterRegion 在应用程序启动时用户位于区域中时不会触发
Swift 4 locationManager didEnterRegion doesn't fire when user is in region on app launch
我正在尝试检测用户是否在我的应用中进入特定区域。
如果用户在应用启动并进入特定区域时不在特定区域,则此方法工作正常。
但如果应用启动时用户在特定区域,则不会触发 "didEnterRegion" 功能。
这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
self.dbRef = Database.database().reference()
self.mapView.delegate = self
self.initLocationManager()
guard let userLocation = locationManager.location?.coordinate else {return}
self.userLocation = userLocation
let region = MKCoordinateRegion(center: userLocation, latitudinalMeters: 1200, longitudinalMeters: 1200)
mapView.setRegion(region, animated: true)
self.getPlaces { (places) in
self.places = places
self.addAnnotationsToMap(places)
if(CLLocationManager.authorizationStatus() == .authorizedAlways){
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self){
for place in places{
self.startMonitoring(place)
}
}
}
}
}
func startMonitoring(_ place: Place){
let region = CLCircularRegion(center: place.getCoordinate(), radius: 50, identifier: place.identifier)
region.notifyOnEntry = true
region.notifyOnExit = true
locationManager.startMonitoring(for: region)
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("Entered Region : \(region.identifier)")
}
这是预期的行为,顾名思义,它仅在更广泛的区域交叉时触发。如果要确定用户是在区域内还是区域外,请使用 locationManager.requestState(for region: CLRegion)
然后在委托函数 locationManager(_:didDetermineState:for:)
中接收结果
要查询所有监控区域,请为 locationManager.monitoredRegions
中的每个对象调用 requestState(region)
。
我正在尝试检测用户是否在我的应用中进入特定区域。
如果用户在应用启动并进入特定区域时不在特定区域,则此方法工作正常。
但如果应用启动时用户在特定区域,则不会触发 "didEnterRegion" 功能。
这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
self.dbRef = Database.database().reference()
self.mapView.delegate = self
self.initLocationManager()
guard let userLocation = locationManager.location?.coordinate else {return}
self.userLocation = userLocation
let region = MKCoordinateRegion(center: userLocation, latitudinalMeters: 1200, longitudinalMeters: 1200)
mapView.setRegion(region, animated: true)
self.getPlaces { (places) in
self.places = places
self.addAnnotationsToMap(places)
if(CLLocationManager.authorizationStatus() == .authorizedAlways){
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self){
for place in places{
self.startMonitoring(place)
}
}
}
}
}
func startMonitoring(_ place: Place){
let region = CLCircularRegion(center: place.getCoordinate(), radius: 50, identifier: place.identifier)
region.notifyOnEntry = true
region.notifyOnExit = true
locationManager.startMonitoring(for: region)
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("Entered Region : \(region.identifier)")
}
这是预期的行为,顾名思义,它仅在更广泛的区域交叉时触发。如果要确定用户是在区域内还是区域外,请使用 locationManager.requestState(for region: CLRegion)
然后在委托函数 locationManager(_:didDetermineState:for:)
要查询所有监控区域,请为 locationManager.monitoredRegions
中的每个对象调用 requestState(region)
。