Hello! I have a question. Is there a way to get the last time that the phone was booted? I found this:
ProcessInfo.processInfo.systemUptime
But it give me the time since the last time the phone was turned off, and I need to know the time since the last time the phone was switched on. I don't know if this is possible.
systemUptime
is not the droid you’re looking for. However, the problem is not what you think it is. You wrote:
But it give me the time since the last time the phone was turned off …
which is incorrect. Rather, the problem is sleep.
systemUptime
only counts time while the system has been awake, and our devices sleep a lot.
You can get the boot time (that is, the clock time when the system booted) using the
kern.boottime
sysctl. Here’s a snippet:
func bootTime() -> Date? {
var tv = timeval()
var tvSize = MemoryLayout<timeval>.size
let err = sysctlbyname("kern.boottime", &tv, &tvSize, nil, 0);
guard err == 0, tvSize == MemoryLayout<timeval>.size else {
return nil
}
return Date(timeIntervalSince1970: Double(tv.tv_sec) + Double(tv.tv_usec) / 1_000_000.0)
}
Be aware that this time will change if the system clock changes, that is, the value is the boot time relative to the current system clock.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"