Is there a way to get system uptime in iOS (using Swift)? What I need is to measure time without having to worry about the user changing the time. In Android there's a elapsedCurrentTimeMillis()
that returns the number of milliseconds since boot, but now I need something like that for iOS. There's an accepted answer here Getting iOS system uptime, that doesn't pause when asleep but that's for Objective C and I need it for Swift and I don't know how to convert it.
As you ask for a pure-Swift solution, I converted the ObjC code from the answer you mentioned Getting iOS system uptime, that doesn't pause when asleep.
func uptime() -> time_t {
var boottime = timeval()
var mib: [Int32] = [CTL_KERN, KERN_BOOTTIME]
var size = strideof(timeval)
var now = time_t()
var uptime: time_t = -1
time(&now)
if (sysctl(&mib, 2, &boottime, &size, nil, 0) != -1 && boottime.tv_sec != 0) {
uptime = now - boottime.tv_sec
}
return uptime
}
// print(uptime())
To make it a bit prettier, we can use sysctlbyname
instead of sysctl
:
// var mib: [Int32] = [CTL_KERN, KERN_BOOTTIME]
sysctlbyname("kern.boottime", &boottime, &size, nil, 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With