将要通过网络发送/接收的日期(绝对时间)转换为 Swift 中的数据? [英] Convert a Date (absolute time) to be sent/received across the network as Data in Swift?

查看:13
本文介绍了将要通过网络发送/接收的日期(绝对时间)转换为 Swift 中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种 Swifty 方式来生成时间戳.

I am looking for a Swifty way to generate a timestamp.

我的 macOS 应用程序会记录一些数据并在数据创建时间上打上标记.然后,数据将通过网络发送(作为 Data)在 iPad 上重建.

My macOS app logs some data and stamps it with the time the data was created. The data will then be sent across the network (as Data) to be reconstructed on an iPad.

是否有任何 Swift 类可以生成时间戳?国安日期?NSTimeIntervalSince1970?CFAbsoluteTimeGetCurrent()

Is there any Swift class that will work to generate the timestamp? NSDate? NSTimeIntervalSince1970? CFAbsoluteTimeGetCurrent()

要求是:

  1. 将时间戳存储在尽可能少的字节中(pref. Int)
  2. 与真实的地球时间有些相似(我宁愿不生成我的自己的时间格式)
  3. 毫秒精度
  4. 快速构建
  5. iOS 9+、macOS 10.10+

推荐答案

您可以发送您的 Date 并将其转换为 Data(8 字节浮点)并返回日期如下:

You can send your Date converting it to Data (8-bytes floating point) and back to Date as follow:

extension Numeric {
    var data: Data {
        var source = self
        return .init(bytes: &source, count: MemoryLayout<Self>.size)
    }
    init<D: DataProtocol>(_ data: D) {
        var value: Self = .zero
        let size = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} )
        assert(size == MemoryLayout.size(ofValue: value))
        self = value
    }
}

<小时>

extension UInt64 {
    var bitPattern: Double { .init(bitPattern: self) }
}

<小时>

extension Date {
    var data: Data { timeIntervalSinceReferenceDate.bitPattern.littleEndian.data }
    init<D: DataProtocol>(data: D) {
        self.init(timeIntervalSinceReferenceDate: data.timeIntervalSinceReferenceDate)
    }
}

<小时>

extension DataProtocol {
    func value<N: Numeric>() -> N { .init(self) }
    var uint64: UInt64 { value() }
    var timeIntervalSinceReferenceDate: TimeInterval { uint64.littleEndian.bitPattern }
    var date: Date { .init(data: self) }
}

<小时>

游乐场测试


Playground Testing

let date = Date()            // "Nov 15, 2019 at 12:13 PM"
let data = date.data         // 8 bytes
print(Array(data))           // "[25, 232, 158, 22, 124, 191, 193, 65]
"
let loadedDate = data.date   // "Nov 15, 2019 at 12:13 PM"
print(date == loadedDate)    // "true"

这篇关于将要通过网络发送/接收的日期(绝对时间)转换为 Swift 中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆