Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting system uptime in iOS/Swift

Tags:

ios

swift

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.

like image 865
TimSim Avatar asked Nov 27 '22 16:11

TimSim


1 Answers

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)
like image 134
Donghua Li Avatar answered Dec 05 '22 15:12

Donghua Li