本文介绍了在iOS / Swift中获得系统正常运行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让iOS系统正常运行(使用Swift)?我需要的是测量时间而不必担心用户改变时间。在Android中有一个 elapsedCurrentTimeMillis(),它返回自启动以来的毫秒数,但现在我需要类似iOS的东西。这里有一个公认的答案但这是针对目标C而我需要它用于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.

推荐答案

当你要求一个纯粹的Swift解决方案时,我从你提到的答案转换了ObjC代码。

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())






为了让它更漂亮,我们可以使用 sysctlbyname 而不是 sysctl

// var mib: [Int32] = [CTL_KERN, KERN_BOOTTIME]
sysctlbyname("kern.boottime", &boottime, &size, nil, 0)

这篇关于在iOS / Swift中获得系统正常运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 01:21