我希望能够查看用户是否在 Swift 4 中另一个位置的 5 公里半径范围内。
例如:
User Location: 37.785834, -122.406417
Other Location: -117.564011, 48.302353
感谢任何帮助的人!
您可以使用 CLLocationManager 提供的区域监视功能自动检测用户何时自动进入或离开地理区域。
开始监视指定坐标周围的圆区域:
let center = CLLocationCoordinate2D(latitude: 37.785834, longitude: -122.406417)
// Make sure the app is authorized.
if CLLocationManager.authorizationStatus() == .authorizedAlways {
// Make sure region monitoring is supported.
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
// Register the region.
let maxDistance = locationManager.maximumRegionMonitoringDistance
let region = CLCircularRegion(center: center,
radius: 5000.0, identifier: "YourRegionID")
region.notifyOnEntry = true
region.notifyOnExit = false
locationManager.startMonitoring(for: region)
}
}
通过实现 CLLocationManagerDelegate 中的合适方法处理与区域相关的通知(在本例中输入通知(:
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if let region = region as? CLCircularRegion {
// your logic to handle region-entered notification
}
}