-1

如果距离大于 200 米,我会尝试显示警报。我发现每次回到那个页面时,都会再次显示警报,但坐标没有改变。例如,我的应用有两个视图控制器,一个是 mapkit,另一个是位置历史。当我转到显示警报的 mapkit 视图时,这很好,然后我转到位置历史页面并返回到 mapkit 页面,警报再次显示,但坐标尚未更新。所以,我想知道如何在相同的坐标下只显示一次警报。并让alert再次出现,新坐标出现,距离大于200m。我的代码如下所示,它位于viewDidLoad. coordinate0是用户当前位置,coordinate1从 firebase 实时数据库中检索。

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)
}
4

1 回答 1

1

每次显示警报时更新Latitude并使用当前位置。Longitude这样,您始终将当前位置与触发最后警报的最后位置进行比较。

作为旁注,为什么不将位置保存为 aCLLocation而不是两个单独的变量?并且名称变量以小写开头。

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")
}
于 2018-12-03T20:50:02.933 回答