ios - Objective C 到 Swift 代码转换,似乎无法在 Swift 中正确处理字节

标签 ios objective-c swift bluetooth

我正在开发一款简单的 Swift 蓝牙心率监测器 iOS 应用程序。我找到了 this很棒的教程,其中包含 Objective-C 代码。我已将它转换为 Swift,并且正在从我的心率监测器中获取数据。我的问题是我似乎无法在 Swift 中正确访问和转换字节数据。

这是 Objective-C 代码:

// Instance method to get the heart rate BPM information
- (void) getHeartBPMData:(CBCharacteristic *)characteristic error:(NSError *)error
{
    // Get the Heart Rate Monitor BPM
    NSData *data = [characteristic value];      // 1
    const uint8_t *reportData = [data bytes];
    uint16_t bpm = 0;

    if ((reportData[0] & 0x01) == 0) {          // 2
        // Retrieve the BPM value for the Heart Rate Monitor
        bpm = reportData[1];
    }
    else {
        bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));  // 3
    }
    // Display the heart rate value to the UI if no error occurred
    if( (characteristic.value)  || !error ) {   // 4
        self.heartRate = bpm;
        self.heartRateBPM.text = [NSString stringWithFormat:@"%i bpm", bpm];
        self.heartRateBPM.font = [UIFont fontWithName:@"Futura-CondensedMedium" size:28];
        [self doHeartBeat];
        self.pulseTimer = [NSTimer scheduledTimerWithTimeInterval:(60. / self.heartRate) target:self selector:@selector(doHeartBeat) userInfo:nil repeats:NO];
    }
    return;
}

这是 Swift 代码:

func peripheral(peripheral: CBPeripheral!,
    didUpdateValueForCharacteristic characteristic: CBCharacteristic!,
    error: NSError!) -> String
{

    // Get the Heart Rate Monitor BPM
    var data = characteristic.value
    var reportData = data.bytes
    var bpm : UInt16
    var rawByte : UInt8
    var outputString = ""
    rawByte = UInt8(reportData[0])
    bpm = 0

    if ((rawByte & 0x01) == 0) {          // 2
        // Retrieve the BPM value for the Heart Rate Monitor
        bpm = UInt16( reportData[4] )
    }
    else {
        bpm = CFSwapInt16LittleToHost(UInt16(reportData[1]))
    }

    outputString = String(bpm)
    return outputString
}

最佳答案

const uint8_t *reportData = [data bytes];

翻译成

let reportData = UnsafePointer<UInt8>(data.bytes)

然后 reportData类型为 UnsafePointer<UInt8>您可以像在 (Objective-)C 中那样访问它:

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

下一步,

bpm = reportData[1];

在 Swift 中几乎相同。您必须从 UInt8 显式转换至 UInt16因为——与 (Objective-)C 不同——Swift 不会在类型之间隐式转换:

bpm = UInt16(reportData[1]) 

综合:

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

    // ...
}

请注意,您的大部分变量都可以用 let 声明为常量 , 反而 的 var .而不是

bpm = CFSwapInt16LittleToHost(bpm)

您也可以使用 littleEndian:可用的构造函数 对于所有整数类型:

bpm = UInt16(littleEndian: bpm)

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 } )
    }

    // ...
}

关于ios - Objective C 到 Swift 代码转换,似乎无法在 Swift 中正确处理字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27947626/

相关文章:

iphone - 即使配置正确,URLForUbiquityContainerIdentifier 也会返回 nil

ios - 根据与位置的距离计算 MAX 和 MIN 纬度和经度 - Objective-C

ios - 如何通过 CBL2CAPChannel 发送和接收数据

iOS 是否可以只使用最大尺寸的图标文件?

ios - StackNavigation 如何知道我从哪个屏幕导航?

ios - 网络扩展 - 权利

ios - 用单位标记核心图轴

ios - 如何在另一个自定义表格 View 中快速创建自定义表格 View

ios - 苹果 ARKit 示例代码

ios - 做CABeginAnimation时如何正确设置模型