How can I make a function execute every second in swift?

后端 未结 7 1759
离开以前
离开以前 2020-11-29 01:59

I want to add a score to the top of my scene in the game I am working on. The score is going to based on how long you last, and will increase every second. Thanks for the he

相关标签:
7条回答
  • 2020-11-29 02:39

    There is something called NSTimer in swift which could solve your problem. I have given an example like how you can use it. Just customise it for your purpose.

    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
                                                       target: self, 
                                                       selector: Selector("yourMethodToCall"), 
                                                       userInfo: nil, 
                                                       repeats: true)
    

    Add this line to the place where you need to call your function repeatedly.

    1. The 1.0 refers to 1 second.
    2. Change the selector to call yourMethodName
    3. repeats is set to true to call that function every second.

    Try this out and let me know if your are stuck somewhere. Thanks.

    0 讨论(0)
  • 2020-11-29 02:40

    I prefer

    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()          
    
        timer =  Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in                
            // Do what you need to do repeatedly         
        }
    }
    

    To stop it:

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }
    
    0 讨论(0)
  • 2020-11-29 02:44

    Swift 3

    find this solution it worked for me

    weak var timer: Timer?
    var timerDispatchSourceTimer : DispatchSourceTimer?
    
    func startTimer() {
        if #available(iOS 10.0, *) {
            timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] _ in
                // do something here
    
            }
    
        } else {
            // Fallback on earlier versions
            timerDispatchSourceTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
            timerDispatchSourceTimer?.scheduleRepeating(deadline: .now(), interval: .seconds(60))
            timerDispatchSourceTimer?.setEventHandler{
                    // do something here
    
            }
            timerDispatchSourceTimer?.resume()
        }
    }
    
    func stopTimer() {
        timer?.invalidate()
        //timerDispatchSourceTimer?.suspend() // if you want to suspend timer 
        timerDispatchSourceTimer?.cancel()
    }
    
    // if appropriate, make sure to stop your timer in `deinit`
    deinit {
        stopTimer()
    }
    
    0 讨论(0)
  • 2020-11-29 02:45

    Xcode 10.2 Swift 5:

    override func viewDidLoad() {
        super.viewDidLoad()
        // ...
        Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: Selector(("your @obcj func name")), userInfo: nil, repeats: true)
    }
    
    //Anywhere in the same view controller to stop the loop:
    Timer.cancelPreviousPerformRequests(withTarget: your @obcj func name())
    
    0 讨论(0)
  • 2020-11-29 02:49

    I don't think you need NSTimer for this.

    Since you are using SpriteKit, I am going to suggest simplest solution in my opinion:

    Declare a variable var prevScoreCalcTime:TimeInterval = 0

    Inside of update func in your GameScene set it up like below:

    override func update(_ currentTime: TimeInterval) {
        if currentTime - prevScoreCalcTime > 1 {
            prevScoreCalcTime = currentTime
            // Any function you put here will execute every second
        }
    }
    

    Good luck!

    0 讨论(0)
  • 2020-11-29 03:01

    You can use one like this:

    var timer = NSTimer()
    
    override func viewDidLoad() {
        scheduledTimerWithTimeInterval()
    }
    
    func scheduledTimerWithTimeInterval(){
        // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateCounting"), userInfo: nil, repeats: true)
    }
    
    func updateCounting(){
        NSLog("counting..")
    }
    

    Swift 3:

    var timer = Timer()
    
    override func viewDidLoad() {               // Use for the app's interface
        scheduledTimerWithTimeInterval()
    }
    
    override func didMove(to view: SKView) {    // As part of a game
        scheduledTimerWithTimeInterval()
    }
    
    func scheduledTimerWithTimeInterval(){
        // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)
    }
    
    @objc func updateCounting(){
        NSLog("counting..")
    }
    
    0 讨论(0)
提交回复
热议问题