Getting system uptime in iOS/Swift

Viewed 8230

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.

4 Answers

Updated for Swift 5 and straight from ADF post here:

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."

Related