5 Replies
      Latest reply on May 3, 2018 2:09 PM by Bjvb09
      Bjvb09 Level 1 Level 1 (0 points)

        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.

        • Re: System Uptime
          Claude31 Level 8 Level 8 (7,295 points)

          That's a bit surprising, as doc states :

           

          var systemUptime: TimeInterval

          The amount of time the system has been awake since the last time it was restarted.

          • Re: System Uptime
            eskimo Apple Staff Apple Staff (12,475 points)

            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"