2015-11-06 79 views
1

我一直在使用nrf51x。我有一个用Obj-C编写的示例代码。我无法将其转换为Swift。将Objective-C代码转换为Swift

uint8_t value = ACTIVATE_AND_RESET_REQUEST; 
[self.bluetoothPeripheral writeValue:[NSData dataWithBytes:&value length:sizeof(value)] forCharacteristic:self.dfuControlPointCharacteristic type:CBCharacteristicWriteWithResponse]; 

我试图

var value: UInt8 = DfuOperations.VALIDATE_FIRMWARE_REQUEST.rawValue 
let ptr = UnsafePointer<Void>(value) 
let data = NSData(ptr, length: sizeofValue(value)) 
dfuPeripheral!.writeValue(data, forCharacteristic: self.dfuControlPointCharacteristic, type: CBCharacteristicWriteType.WithResponse) 

而这一次

var value: UInt8 = DfuOperations.VALIDATE_FIRMWARE_REQUEST.rawValue 
let data = NSData(&value, length: sizeofValue(value)) 

任何一个能帮助我吗? 非常感谢你

+0

阅读本[答案]提供的链接(http://stackoverflow.com/a/33564737/5222077) – kye

+0

@kye此工具提供的转换不起作用。 –

+0

我不认为它更新到迅速2.1尚未 – kye

回答

0

感谢@Robert答案我找到了解决方案。 我最终创建了一个将[UInt8]数组写入CBCharacteristic的方法。 下面是代码:

func updateValueForCharacteristic(characteristic: CBCharacteristic, value: [UInt8], writeType: CBCharacteristicWriteType = CBCharacteristicWriteType.WithResponse){ 
    let data = NSData(bytes: value, length: sizeofValue(value)) 
    dfuPeripheral!.writeValue(data, forCharacteristic: characteristic, type: writeType) 
} 
0

下面的类建立没有错误。我正在使用Xcode 7.1。

import Foundation 
import CoreBluetooth 

class Test { 
    func test(bluetoothPeripheral: CBPeripheral, dfuControlPointCharacteristic: CBCharacteristic) { 
     let value = UInt8(ACTIVATE_AND_RESET_REQUEST.rawValue) 
     let encodedValue = NSData(bytes: [value], length: sizeof(UInt8)) 
     bluetoothPeripheral.writeValue(encodedValue, forCharacteristic: dfuControlPointCharacteristic, type: CBCharacteristicWriteType.WithResponse) 
    } 
} 
+0

为什么在原始代码使用'UInt8'时使用'UInt32'? – Sulthan

+0

@Sulthan:你说得对。我修改了代码 – Verticon

+0

谢谢@RobertVaessen –