• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在iOS / Swift获得系统正常运行时间

用户头像
it1352
帮助1

问题说明

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

正确答案

#1

当你要求一个纯粹的Swift解决方案时,我从你提到的答案转换了ObjC代码让iOS系统正常运行,睡着时不会暂停

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)

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfjhbb
系列文章
更多 icon
同类精品
更多 icon
继续加载