Search code examples
iosswiftswift2uptime

NSProcessInfo().systemUptime is wrong


I have a trouble with getting NSTimeInterval after system reboot. This functions gave me a wrong result. The reboot time is restarting when device's battery is charged. There is a trouble on iPhone 5s and iPad 3 (the new). How can I fix it?


Solution

  • I use this method and it helps me

     public static func uptime() -> (days: Int, hrs: Int, mins: Int, secs: Int) {
                var currentTime = time_t()
                var bootTime    = timeval()
                var mib         = [CTL_KERN, KERN_BOOTTIME]
    
                // NOTE: Use strideof(), NOT sizeof() to account for data structure
                // alignment (padding)
                // http://stackoverflow.com/a/27640066
                // https://devforums.apple.com/message/1086617#1086617
                var size = strideof(timeval)
    
                let result = sysctl(&mib, u_int(mib.count), &bootTime, &size, nil, 0)
    
                if result != 0 {
                    #if DEBUG
                        print("ERROR - \(__FILE__):\(__FUNCTION__) - errno = "
                            + "\(result)")
                    #endif
    
                    return (0, 0, 0, 0)
                }