Swift withUnsafeBytes

一个蓝牙的项目,需要从蓝牙获取数据。方便起见使用了iPhoneXS进行测试,内容是获取XS蓝牙提供的服务内容,并且能够读取数据。测试后拿到的数据如下:

提供的服务UUID  Continuity  ->  D0611E78-BBB4-4591-A5F8-487910AE4366
提供的服务UUID  9FA480E0-4967-4542-9390-D343DC5D04AE  ->  9FA480E0-4967-4542-9390-D343DC5D04AE
提供的服务UUID  Battery  ->  180F
提供的服务UUID  Current Time  ->  1805
提供的服务UUID  Device Information  ->  180A

这里显示了不同的属性 uuiduuid.uuidString。之后在尝试从Data里边拿出Current Time的时候发现Swift4.0 和 5.0,在使用withSafeBytes时有略微差别。

            let array = data.withUnsafeBytes {
                                (pointer: UnsafePointer<Int8>) -> [Int8] in
                let buffer = UnsafeBufferPointer(start: pointer,
                                                 count: data.count)
                return Array<Int8>(buffer)
            print(array);
           let array = data.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> [Int8] in
            if let ptrAddress = pointer.baseAddress, pointer.count > 0 {
                let pointer = ptrAddress.assumingMemoryBound(to: Int8.self) // here you got UnsafePointer<UInt8>
                let buffer = UnsafeBufferPointer(start: pointer,count: data.count)
                return Array<Int8>(buffer)
            return Array<Int8>()
            print("我的消息是 ",array)