2015-11-06 72 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 –