如果距离大于200米,我会尝试显示警报。我每次回到该页面时都会发现警报再次显示,但是坐标没有更改。例如,我的应用程序有两个视图控制器,一个是mapkit,另一个是位置历史记录。当我转到显示警报的mapkit视图时,这很好,然后我转到位置历史记录页面并返回mapkit页面,警报再次显示,但是坐标尚未更新。因此,我想知道如何仅在相同坐标下一次显示警报。并以新的坐标出现并且距离大于200m再次显示警报。我的代码如下所示,位于viewDidLoad
下。 coordinate0
是用户当前位置,并且从Firebase实时数据库中检索coordinate1
。
self.createAnnotation(locations: [annotationLocations])
let coordinate0 = CLLocation(latitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.longitude)!)
let coordinate1 = CLLocation(latitude: Latitude as! CLLocationDegrees, longitude: Longtitude as! CLLocationDegrees)
let distance = coordinate0.distance(from: coordinate1)
if (distance <= 200) {
print(distance)
} else {
self.creatAlert(title: "Is it you?", message: "Hi")
}
我的警报功能代码如下所示。
func creatAlert (title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
print("Yes")
}))
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
print("No")
}))
self.present(alert, animated: true, completion: nil)
}
答案 0 :(得分:1)
使用当前位置更新Latitude
和Longitude
。这样,您就可以始终将当前位置与触发上一个警报的最后位置进行比较。
请注意,为什么不将位置另存为CLLocation
而不是两个单独的变量?和以小写字母开头的名称变量。
self.createAnnotation(locations: [annotationLocations])
let coordinate0 = CLLocation(latitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.longitude)!)
let coordinate1 = CLLocation(latitude: Latitude as! CLLocationDegrees, longitude: Longtitude as! CLLocationDegrees)
let distance = coordinate0.distance(from: coordinate1)
if (distance <= 200) {
print(distance)
} else {
Latitude = coordinate0.coordinate.latitude
Longitude = coordinate0.coordinate.longitude
self.creatAlert(title: "Is it you?", message: "Hi")
}