Issue when trying to append timer to array of String to show them in tableView

So I have a var timerPerChat: Array<String> = [] and a var meterTimer: Timer! as variables .

In the meterTimer I’m saving self.meterTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self,selector:#selector(self.updateAudioMeter(_:)),userInfo: nil,repeats: true)

with the selector

    @objc func updateAudioMeter(_ timer: Timer) {

    if let recorder = self.soundRecorder {
        if recorder.isRecording {
            let min = Int(recorder.currentTime / 60)
            let sec = Int(recorder.currentTime.truncatingRemainder(dividingBy: 60))
            let s = String(format: "%02d:%02d", min, sec)
            timerPerChat.append(s)
            recorder.updateMeters()
        }
    }
}

In my tableView cellForRow I have like :

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyMessageTableViewCell", for: indexPath) as! MyMessageTableViewCell
    cell.statusChatTimerLabel.text = timerPerChat[indexPath.row]
    return cell
}

The thing is i always get 00:00 and when i put a breakpoint here to see what timerPerChat holds i got

po timerPerChat
? 100 elements
– 0 : “00:00”
– 1 : “00:00”
– 2 : “00:00”
– 3 : “00:00”
– 4 : “00:00”
– 5 : “00:00”
– 6 : “00:00”
– 7 : “00:00”
– 8 : “00:00”
– 9 : “00:01”
– 10 : “00:01”
– 11 : “00:01”
– 12 : “00:01”
– 13 : “00:01”
– 14 : “00:01”
– 15 : “00:01”
– 16 : “00:01”
– 17 : “00:01”
– 18 : “00:01”
– 19 : “00:00”

so thats why i m guessinng i always get 00:00 since my indexPath.row 0 is 00:00 till indexpath.row 8. But still I dont know where I m wrong.

Multiple timers at once ios

I am making an app where the user can have multiple timers going at once and see them in a list view.

I am aware that there are 2 main options for working out time:

  • Subtract the date started from current date (current date-start date)

OR

  • Use an NSTimer and take away 1 second every second from each active timer.

I have previously been using the latter, but having looked around the internet I am starting to think that the data one may be better.

Please could you let me know which you think is best to use, and if you chose the first one (dates), please could you provide some sample code on how to use it.

How to set up a timer and display it on a game scene with Swift [duplicate]

I am trying to set up a timer that counts from 60 seconds to 0 and display the count on my game scene. However, I keep running into issues when I do the following:
In my GameScene.swift file I created the following:

 var gameTimer = 60
 var timer = Timer()
 @IBOutlet var timerLabel: UILabel!

under the GameScene class, then under the ViewDidLoad I did:

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameViewController.startTimer), userInfo: nil, repeats: true)

where startTimer was a function with the following content:

    @objc func startTimer()  {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameViewController.updateTimer), userInfo: nil, repeats: true)
}

and updateTimer is another function to update the timer:

    @objc func updateTimer(){
    gameTimer -= 1
    timerLabel.text = String(gameTimer)

}

But the game keeps crashing when I launch it. What am I doing wrong here? Any help is appreciated.

For those of you who asked about the error message:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

And it is pointing to this line of code:

        timerLabel.text = String(gameTimer)

NSImageView update delayed when set from an NSTimer

I’m working on a project in Swift that requires strict control of image display and removal timings in certain sections. I’m finding that when I set the image property of an NSImageView from inside a block that’s fired by a Timer, the actual display of the image on the screen is delayed by up to a second after the assignment is complete. (This is measured by eyeballing it and using a stopwatch to gauge the time between when an NSLog line is written and when the image actually appears on-screen.)

Triggering image display with a click appears to happen instantaneously, whether it’s done by setting the image property of an existing NSImageView, or constructing one on the spot and adding it as a subview.

I have attempted to reduce the behavior down to a fairly simple test case, which, after basic setup of the view (loading the images into variables and laying out several target image locations, which are NSImageViews stored to the targets array), sets a Timer, with an index into the targets array stored in its userInfo property, to trigger the following method:

@objc func testATimer(fromTimer: Timer) {
    if let targetLocation = fromTimer.userInfo as? Int {
        NSLog("Placing target \(targetLocation)")
        targets[targetLocation].image = targetImage

        OperationQueue.main.addOperation {
            let nextLocation = targetLocation + 1
            if (nextLocation < self.targets.count) {
                NSLog("Setting timer for target \(nextLocation)")
                let _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(ViewController.testATimer(fromTimer:)), userInfo: nextLocation, repeats: false)
            }
        }
    }
}

The amount of time observed between the appearance of the log entry “Placing target x” and that of the image that is set to be displayed in the very next line seems to average between 0.3 and 0.6 seconds. This is far beyond the delay that this project can tolerate, as the image will only be on screen for a total of 1 second at a time.

My best guess as to why this is happening is that it is something to do with Timers running on a separate thread from the main display thread; however, I do not have enough experience with multi-threaded programming to know exactly how to mitigate that.

Any assistance would be most appreciated, and if I’ve left out information that would make answering easier (or possible) I’m more than happy to give it.

NSImageView update delayed when set from an NSTimer

I’m working on a project in Swift that requires strict control of image display and removal timings in certain sections. I’m finding that when I set the image property of an NSImageView from inside a block that’s fired by a Timer, the actual display of the image on the screen is delayed by up to a second after the assignment is complete. (This is measured by eyeballing it and using a stopwatch to gauge the time between when an NSLog line is written and when the image actually appears on-screen.)

Triggering image display with a click appears to happen instantaneously, whether it’s done by setting the image property of an existing NSImageView, or constructing one on the spot and adding it as a subview.

I have attempted to reduce the behavior down to a fairly simple test case, which, after basic setup of the view (loading the images into variables and laying out several target image locations, which are NSImageViews stored to the targets array), sets a Timer, with an index into the targets array stored in its userInfo property, to trigger the following method:

@objc func testATimer(fromTimer: Timer) {
    if let targetLocation = fromTimer.userInfo as? Int {
        NSLog("Placing target \(targetLocation)")
        targets[targetLocation].image = targetImage

        OperationQueue.main.addOperation {
            let nextLocation = targetLocation + 1
            if (nextLocation < self.targets.count) {
                NSLog("Setting timer for target \(nextLocation)")
                let _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(ViewController.testATimer(fromTimer:)), userInfo: nextLocation, repeats: false)
            }
        }
    }
}

The amount of time observed between the appearance of the log entry “Placing target x” and that of the image that is set to be displayed in the very next line seems to average between 0.3 and 0.6 seconds. This is far beyond the delay that this project can tolerate, as the image will only be on screen for a total of 1 second at a time.

My best guess as to why this is happening is that it is something to do with Timers running on a separate thread from the main display thread; however, I do not have enough experience with multi-threaded programming to know exactly how to mitigate that.

Any assistance would be most appreciated, and if I’ve left out information that would make answering easier (or possible) I’m more than happy to give it.

Swift 3 timer is nil after being set?

I’m trying to use a timer to check whether a response has been received from a BLE device. Since the BLE class communicates with the rest of the app using NSNotifications, most of the actions are initiated from off the main thread. Also, the timers are calling back to a function in a parent class. Here is how it’s set up in the child class:

private var responseTimer: Timer?
let itemID: Int  // set at object initialization

func startResponseTimerWithTarget(_ target: MyViewControllerClass) {
    self.clearResponseTimer()
    self.responseTimer = Timer.scheduledTimer(timeInterval: self.kResponseTimerDuration, target: target, selector: #selector(MyViewControllerClass.responseTimerFired), userInfo: self.itemID, repeats: false)
    debugPrint("Starting timer \(self.responseTimer) id \(self.itemID)")
}

func clearResponseTimer() {
    debugPrint("Clearing timer \(self.responseTimer) id \(self.itemID)")
    if responseTimer != nil {
        responseTimer?.invalidate()
        responseTimer = nil
    }
}

All actions controlling the timer from the parent class are driven by notifications, and are wrapped in DispatchQueue.main.async {} calls. When the timer is started, the print statement immediately afterwards prints the object pointer. However, when clearResponseTimer is called due to another notification later, the timer is found to be nil, even though it isn’t weak, and the call is still wrapped in DispatchQueue.main.async {}, and the timer will fire regardless. Later on, from a notification driven by the BLE device disconnecting, the clear timer function does work and finds a non-null Timer, with the same pointer as the timer that was originally created.

I’m really puzzled here; I’ve never had this kind of trouble with timers before and it seems that something strange is going on. I’m unsure of why the object could appear to be nil, even though it was explicitly set and checked earlier, and there is no other code that accesses or modifies the timer.

xcode 9.2 iOS swift timer

I used Xcode and swift a few years ago and have now returned and I’m trying to make a timer that execute a procedure every second. But with this new swift and Xcode 9.2, NSTimer and Timer.scheduledTimer no longer exist ans I can’t find any documentation on how you make a timer in this new version of Xcode. Can any one help and tell me how to do this. Thanks in advance.

How can i restrict multiple timer function calling a function at same time? Swift 3+

I have 5 timers running with a different time interval.All these timers calling the same function.
At a certain time, one or more timer function trying to access the same method, this will crash my app.

How I can implement NSOperation queue for this particular scenario.

Appreciate your help.