Objective C to Swift code conversion, can't seem to treat bytes correctly in Swift

前端 未结 1 1231
暗喜
暗喜 2021-02-11 00:57

I\'m working on a simple Swift bluetooth heart rate monitor iOS App. I found this great tutorial which has objective C code. I\'ve converted it to Swift and I\'m getting data fr

1条回答
  •  醉话见心
    2021-02-11 01:23

    const uint8_t *reportData = [data bytes];
    

    translates to

    let reportData = UnsafePointer(data.bytes)
    

    Then reportData has the type UnsafePointer and you can access it as in (Objective-)C:

    if (reportData[0] & 0x01) == 0 { ... }
    

    Next,

    bpm = reportData[1];
    

    is almost identical in Swift. You have to convert explicitly from UInt8 to UInt16 because – unlike (Objective-)C – Swift does not implicitly convert between types:

    bpm = UInt16(reportData[1]) 
    

    Putting it together:

    func getHeartBPMData(characteristic: CBCharacteristic!) {
        let data = characteristic.value
        let reportData = UnsafePointer(data.bytes)
        var bpm : UInt16
        if (reportData[0] & 0x01) == 0 {
            bpm = UInt16(reportData[1])
        } else {
            bpm = UnsafePointer(reportData + 1)[0]
            bpm = CFSwapInt16LittleToHost(bpm)
        }
    
        // ...
    }
    

    Note that most of your variables can be declared as constants with let, instead of var. Instead of

    bpm = CFSwapInt16LittleToHost(bpm)
    

    you can alternatively use the littleEndian: constructor which is available for all integer types:

    bpm = UInt16(littleEndian: bpm)
    

    Update for Swift 3/4:

    func getHeartBPMData(characteristic: CBCharacteristic) {
        guard  let reportData = characteristic.value else {
            return 
        }
    
        let bpm : UInt16
        if (reportData[0] & 0x01) == 0 {
            bpm = UInt16(reportData[1])
        } else {
            bpm = UInt16(littleEndian: reportData.subdata(in: 1..<3).withUnsafeBytes { $0.pointee } )
        }
    
        // ...
    }
    

    0 讨论(0)
提交回复
热议问题