我想检查用户是否在附近。例如,我已指定用户当前位置周围50米的半径。假设用户是否在移动,现在我要检查用户是否在50米半径范围内。这是我的代码
override func viewDidLoad() {
super.viewDidLoad()
locationManager.startMonitoringVisits()
locationManager.delegate = self
locationManager.distanceFilter = 1
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
}
这是检查距离的代码
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
return
}
let officeLocation = CLLocationCoordinate2D.init(latitude: 31.471303736482234, longitude: 74.27275174139386)
let circle = MKCircle(center: officeLocation, radius: 50 as CLLocationDistance)
if location.distance(from: officeLocation) > circle.radius {
self.newVisitReceived(des: "YOU ARE OUT OF OFFICE")
}
else{
self.newVisitReceived(des: "YOU ARE IN OFFICE")
}
}
即使我不移动此代码,也会发送通知“ YOU ARE OUT”。
答案 0 :(得分:0)
定位服务的普遍问题是,测量的准确性会有所不同,这取决于许多因素。如果用户站在50米的边界上,您希望代码的行为如何?如果准确性很差,那么您当前的代码将在“在办公室”和“不在办公室”之间随机地来回切换。
我认为在最佳条件下,GPS的精度实际上超过4米,因此distanceFilter为1可能不合适。
我想您可能需要在应用中使用某种状态来跟踪何时用户在50米半径内的最后一次出现,还需要一些宽限期才能再次更新该变量,以避免“闪烁”
答案 1 :(得分:0)
我会用Geofences解决这个问题... 您必须指定坐标中心和半径,以便用户在地理围栏的内部/外部进入时要在该位置收听。
override func viewDidLoad() {
super.viewDidLoad()
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.allowsBackgroundLocationUpdates = true
locationManager.requestAlwaysAuthorization()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways || status == .authorizedWhenInUse {
// CLLocationCoordinate2D; You have to put the coordinate that you want to listen
let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: 324234, longitude: 23423), radius: 50, identifier: "Ur ID")
region.notifyOnExit = true
region.notifyOnEntry = true
manager.startMonitoring(for: region)
}
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
// User has exited from ur regiom
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
// User has exited from ur region
}
我希望这会有用