Apix_D
Apix_D

Reputation: 1101

How to count Timer on Swift

I'm a newbie in swift and I tried to make a Timer. It should normally count the seconds and print them in the debugger.

I tried this:

var timer = Timer() 

@IBAction func killTimer(_ sender: AnyObject) {
    timer.invalidate()         
}

@objc func processTimer() {
    print("This is a second")
}

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.processTimer), userInfo: nil, repeats: true)
}

I don't know how the timer count seconds.. With this code i get an fail message:

@objc func processTimer() {
    print("This is second \(Timer + 1)")
}

Thanks for your help. A

Upvotes: 4

Views: 10668

Answers (3)

vadian
vadian

Reputation: 285059

You need a counter variable which is incremented every time the timer fires.

Declare the variable Timer as optional to invalidate the timer reliably (only once).

var timer : Timer?
var counter = 0 

@IBAction func killTimer(_ sender: AnyObject) {
   timer?.invalidate()
   timer = nil
}

@objc func prozessTimer() {
    counter += 1
    print("This is a second ", counter)

}

override func viewDidLoad() {
    super.viewDidLoad()  
    timer = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(prozessTimer), userInfo: nil, repeats: true)

}

Upvotes: 11

Lukas Würzburger
Lukas Würzburger

Reputation: 6673

If you want to print the time that passed use this (If that's what you want):

print("time passed: \(Date().timeIntervalSince1970 - timer.fireDate.timeIntervalSince1970)")

Upvotes: 0

Joakim Danielson
Joakim Danielson

Reputation: 51861

You need to start your timer, you have only initialised it in your code so in viewDidLoad add

timer.fire()

I am not sure what you want to print but if it is a timestamp then you could do add a property to your class

let formatter = DateFormatter()

and configure it to show time in seconds and milliseconds

formatter.dateFormat = "ss.SSS" //in viewDidLoad

and use it in your print statement

print("This is a second \(formatter.string(from(Date())")

Upvotes: 0

Related Questions