你如何从JavaScript传递NSData?

时间:2015-11-30 21:51:46

标签: objective-c react-native

我正在创建一个使用CoreBluetooth.framework的本机模块。我正在尝试实施一个RCT_EXPORT_METHOD来调用this bluetooth write method

RCT_EXPORT_METHOD(write:(CBUUID *)peripheralUuid 
                  forCharacteristicUuid:(CBUUID *)characteristicUuid 
                  data:(NSData *)data /* <== HOW DO I PASS THIS IN? */
                  withResponse:(BOOL)withResponse)
{
    CBPeripheral *peripheral = /* my peripheral */;
    CBCharacteristic *characteristic = /* my characteristic */;

    if (peripheral && characteristic) {
        [peripheral 
              writeValue:data 
              forCharacteristic:characteristic 
              type:withResponse ? 0 : 1];
    }
}

我需要使用RCTConvert通过本机网桥获取NSData参数?

1 个答案:

答案 0 :(得分:2)

在对source code进行进一步研究后,我发现你无法声明NSData参数,你必须将其作为base64编码的字符串(NSString)传递,然后使用RCTConvert将其转换为NSData

RCT_EXPORT_METHOD(write:(CBUUID *)peripheralUuid 
                  forCharacteristicUuid:(CBUUID *)characteristicUuid 
                  data:(NSString *)data
                  withResponse:(BOOL)withResponse)
{
    // ....
    [peripheral 
          writeValue:[RCTConvert NSData:data] 
          forCharacteristic:/* ... */
          type:/* ... */];
}