NSTimer 未正确执行

NSTimer Not Performing Correctly

我正在开发一款需要大量用户输入的应用程序。因此,我正在尝试构建一个不允许用户 post 更多信息至少 10 秒的功能。这将有助于减少 spammers/trolls/etc。本质上,当用户想要报告某事时,我的应用程序会测量用户与最近的其他报告位置之间的距离。如果他们超过 200 米并且在过去 10 秒内没有报告,那么他们可以自由 post。这是完成此操作的代码:

if( distance > 200 && canPost){
        MainMap.addAnnotation(pointAnnotation)
        canPost = false
        sendTheData(String(locationManager.location?.coordinate.longitude), latitude: String(locationManager.location?.coordinate.latitude), time: getTime(), userId: "admin")
        let myTimer : NSTimer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(MapViewController.postDelayTimer), userInfo: nil, repeats: false)
        myTimer.fire()


    }else if(distance < 200 && canPost){
        let alertController = UIAlertController(title: "Whoa There!", message: "tOO clOSE!", preferredStyle: .Alert)
        let defaultAction = UIKit.UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(defaultAction)
        self.presentViewController(alertController, animated: true, completion: nil)


    }

其他不同的实例依此类推。从计时器调用的函数,postDelayTimer 是这样的:

func postDelayTimer() {
    canPost = true
}

很简单,但显然我在这里遗漏了一些东西。有人有想法吗?谢谢大家!

我预计会发生的是用户在立即 posting 后无法再次 post,但他们能够连续 post。就好像 bool canPost 始终保持为真。

您的密码是:

    let myTimer : NSTimer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(MapViewController.postDelayTimer), userInfo: nil, repeats: false)
    myTimer.fire()

第二行不正确,删除。您不想手动启动计时器。您想等待计时器在 10 秒后自行触发。

两件事:

  1. 您在方法中创建定时器,将定时器初始化为 class 变量并全局使用它。类似于:

    class MapViewController: UIViewController {
        var myTimer = NSTimer()
    
        func activateTimer() {
          myTimer = NSTimer.scheduledTimerWithTimeInterval(10, target:self, selector: #MapViewController.postDelayTimer), userInfo: nil, repeats: true)
        }
    }
    
  2. myTimer.fire() 是不必要的。计时器将在设置后触发。

我通过在按钮 pressed.Inside 之后调用该函数来完成此操作,该函数是一个 NSTimer,当它被触发时,它会继续调用负责对所需布尔值进行字符处理的第三个函数。