NSTimer timerWithTimeInterval not calling selector (Swift)

两盒软妹~` 提交于 2019-12-12 03:45:48

问题


I have tried many approaches that I have found in other questions and any of them are working. My problem is that the timer is not calling selector

class MyViewController: UIViewController{
    var progressBarTimer = NSTimer()
    @IBOutlet weak var progress_bar: UIProgressView!

    override func viewDidLoad() {
        self.progress_bar.progress = 0
        self.progressBarTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(MyViewController.updateProgress(_:)), userInfo: nil, repeats: true)
        //also tried and redefining the updateProgress without timer parameter:
        /*
        *self.progressBarTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(MyViewController.updateProgress), userInfo: nil, repeats: true)
        */
    }
    func updateProgress(timer:NSTimer!) {
        progress_bar.progress += 0.1
        if (progress_bar.progress >= 1) {
           progressBarTimer.invalidate()
        }

    }
}

I have tried to do

progressBarTimer.fire()

and it just executes once the updateProgress function.

Could anyone shed light on? I would really appreciate


回答1:


You can call your function like this:

    let postes = ["1","2","3"]
    let timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "playProgressBar:", userInfo: postes, repeats: true)

and function must like this:

func playProgressBar(timerSender : NSTimer) {

   //Do Somethings

}



回答2:


Replying to myself, I have found the problem. In the previous ViewController I am performing a segue after doing a http connection. In order to make it work, I have embedded the performSegue inside the dispatch:

dispatch_async(dispatch_get_main_queue(), {
    self.performSegueWithIdentifier("goMySecondController", sender: nil)
})

In that second Controller is where I have the Timer that was not working. However, after this change is working properly.

Thanks for replies!



来源:https://stackoverflow.com/questions/36864249/nstimer-timerwithtimeinterval-not-calling-selector-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!