I am migrating a c# app to Xcode swift and have been looking for a swift equivalent to c# Time.time which is the time in seconds since app became active. I have seen the Timer class but all examples I have seen depend on using #selector and @objc. How do I get the Timer class to use a completion function? Or Is there another way of getting the app run time in seconds?
looking for a timer function I can use with using @objc
How do I get the Timer class to use a completion function?
Are you looking for something like this:
let _ = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { myTimer in
print("My Timer Fired")
}
// Or something that ends after 5 seconds....
var repeats = 1
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
print("Timer \(repeats)")
repeats += 1
if repeats > 5 {
timer.invalidate()
}
}
Otherwise, yes, if you are using #selector
you will need to use the @objc
attribute because this interacts with the Objective-C runtime.
class TimerClass: NSObject {
var repeats = 1
var timer: Timer?
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1.0,
target: self,
selector: #selector(objCTimerCallback),
userInfo: nil,
repeats: true)
}
@objc func objCTimerCallback() {
print("Timer: \(repeats)")
repeats += 1
if repeats > 5 {
timer?.invalidate()
}
}
}
let time = TimerClass()
time.startTimer()
Regarding:
Or Is there another way of getting the app run time in seconds?
There is no out-of-the-box API for this but you could look MetricKit if you need more information on app metrics and data.
Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com