Getting system uptime in iOS/Swift

前端 未结 4 1193
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 00:03

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

4条回答
  •  自闭症患者
    2020-12-10 00:45

    Updated for Swift 5 and straight from ADF post here:

    func bootTime() -> Date? {  
        var tv = timeval()  
        var tvSize = MemoryLayout.size  
        let err = sysctlbyname("kern.boottime", &tv, &tvSize, nil, 0);  
        guard err == 0, tvSize == MemoryLayout.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."

提交回复
热议问题