Swift 5 计时器倒计时,而值在一个范围内



我正在尝试从 5 到 0 倒计时,而用户方位距离正北在 20 到 -20 弧度之间。如果轴承保持在 20 和 -20 之间 5 秒,请切换到新控制器。我尝试了一切,但我基本上放弃了。

我尝试了很多东西,包括scheduleTimer(withInterval 1.0){}

我是 Swift 的新手。我无法使计时器失效。

这是获取用户标题

@objc func getUserHeading(_ latitude : Double, _ longitude : Double, _ userLocation : CLLocation){
let lat1 = (latitude) * .pi / 180
let long1 = (longitude) * .pi / 180

let lat2 = (yourLocation.coordinate.latitude) * .pi / 180
let long2 = (yourLocation.coordinate.longitude) * .pi / 180
print(lat1, long1, lat2, long2)

let dLon = long2 - long1

let y = sin(dLon) * cos(lat2)
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)

var radiansBearing = atan2(y, x)
if radiansBearing < 0 {
radiansBearing += 2 * Double.pi
}
theta = (radiansBearing * 180 / .pi) - (angle)
print(theta)
if (theta < 20 && theta > = -20 ){ 
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in 
print("Timer Fired")
runCount += 1
if(theta > 20 && theta < -20)
{
self.timer.invalidate()
self.timerStarted = false
}
if (runCount == 5)
{
self.timer.invalidate()
self.segueToNewController()
}

}
else{
timer.invalidate()
timerStarted = false
}        
}

这可能是语义上的事情,但我发誓我已经花了几天时间,我觉得我无处可去。

迄今为止的问题

  1. 它确实在 20 到 -20 之间触发,但它会立即触发并且不会等待 5 秒
  2. 它触发了很多次
  3. ,这意味着下一个控制器的 segue 被调用了很多次(它导致 5k 写入我的 firestore(

如果你们需要更多,请告诉我,将用更多代码更新问题。 所有的帮助感谢!我的智慧在这里结束

您的代码存在一些问题

  • 您有 2 个相互矛盾的if子句,首先检查theta是否在区间内,然后在if子句内检查相同的值是否在区间之外
  • ,这永远不会发生。
  • 最后的else看起来错位
  • 有些变量您更改但从未读取

我会重写这样的东西(从第一个如果(

if theta < 20 && theta >= -20 {
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print("Timer Fired")
runCount += 1
if runCount == 5 {
timer.invalidate()        
}
//theta = ... here you need to somehow update this property to see if it has changed
if theta > 20 && theta < -20 {
timer.invalidate()                
}
}
} else {
timer?.invalidate()
}

请注意,我删除了timerStarted变量,因为我没有看到拥有它的意义,也没有看到if条件周围不需要括号

最新更新