CMLogItem 时间戳:为什么这么复杂?

CMLogItem timestamp: Why so complicated?

我在 swift 中收到来自 CoreMotion 查询的 CMLogItem(可能是加速度计、陀螺仪)。现在,我想获取该样本的时间戳,最好是 Date() 对象。 CMLogItem 有 属性 .timestamp 类型 TimeInterval

文档告诉我以下内容:

The CMLogItem class defines a read-only timestamp property that records the time a motion-event measurement was taken.

但是,我不确定如何将此时间戳转换为 Date() 对象,因为我不知道时间戳指的是什么。

另一份文件说:

The timestamp is the amount of time in seconds since the device booted.

但这看起来真的很奇怪,我不明白为什么苹果会创建如此不一致和复杂的 API。

我想我明白了。 文档在这里是错误的。 这不是“自设备启动以来的秒数”——它确实是自参考日期以来的时间。

修复:

extension CMLogItem {
    func startTime() -> Date {
        #if os(watchOS)
        return Date(timeIntervalSinceReferenceDate: self.timestamp)
        #else
        let systemRebootTime = Date(timeIntervalSinceNow: -ProcessInfo.processInfo.systemUptime)
        return systemRebootTime.addingTimeInterval(self.timestamp)
        #endif
    }
}

正确答案是:

extension CMLogItem {
    static let bootTime = Date(timeIntervalSinceNow: -ProcessInfo.processInfo.systemUptime)

    func startTime() -> Date {
        return CMLogItem.bootTime.addingTimeInterval(self.timestamp)
    }
}

这为我们提供了稳定、单调的结果,而每次调用 startTime 时都会计算 bootTime 的情况并非如此。