我设置了两个视图控制器,一个UITableView,可以处理所有扫描并连接到设备。一旦发现设备及其服务和特性,我将返回主屏幕,按下按钮,它将数据发送到我连接的外围设备。然而,从我正在阅读的外围设备中没有收到任何信息。 当我尝试从UITableView写入设备时,它确实有效。
以下是按下按钮的代码
- (IBAction)Unlock:(id)sender {
uint8_t val = 12; //data to send
NSData* valData = [NSData dataWithBytes:(void*)&val length:sizeof(val)];
//check if peripheral is connected
if (!myPeriph) {
NSLog(@"Not connected to a peripheral");
}
// check for characteristic
if (!myChar) {
NSLog(@"No valid characteristic");
return;
}
NSLog(@"Writing value for characteristic %@", myChar);
//write data to peripheral
[myPeriph writeValue:valData forCharacteristic:myChar
type:CBCharacteristicWriteWithoutResponse];
}
这是可行的代码
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
// Deal with errors (if any)
if (error) {
NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
// [self cleanup];
return;
}
// Again, we loop through the array, just in case.
for (CBCharacteristic *characteristic in service.characteristics) {
NSLog(@"Discovered characteristic %@",characteristic);
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
// If it is, subscribe to it
//[peripheral setNotifyValue: forCharacteristic:characteristic];
//store characteristic as variable
Connected_Characteristic= characteristic;
NSLog(@"Connected Char %@",Connected_Characteristic);
uint8_t val = 12; //data to send
NSData* valData = [NSData dataWithBytes:(void*)&val length:sizeof(val)];
//write data to peripheral
[Connected_Peripheral writeValue:valData forCharacteristic:Connected_Characteristic
type:CBCharacteristicWriteWithoutResponse];
//pass peripheral and characteristic back to main screen
[self.delegate didSelectWith:self device:Connected_Peripheral device_characteristics:Connected_Characteristic];
//pop back to main screen
[self.navigationController popViewControllerAnimated:YES];
}
}
}
我不确定我做错了什么。我想我可能必须在'didDiscoverCharacteristicsForServices'函数中,但我已经看到另一个在它之外调用write方法的例子。
此外,myPeriph和myChar在这里宣布
-(void)didSelectWith:(deviceViewController *)controller device:(CBPeripheral *)device device_characteristics:(CBCharacteristic *)device_characteristics
{
self.myPeriph=device;
self.myChar=device_characteristics;
[controller dismissViewControllerAnimated:YES completion:nil];
NSLog(@"device %@ characteristic %@ ",myPeriph, myChar);
}
并从上面的函数传递并成功工作。