如何在使用BLE发送消息后获得确认

时间:2016-05-11 11:03:39

标签: ios objective-c bluetooth-lowenergy

我想将文本数据从一个BLE发送到另一个BLE。所以,当我发送" Message1"到" BLE1",如果消息发送成功,我想要一些确认,例如"消息传递给BLE1"成功

我使用以下代码:

  -(void) writeValue:(CBUUID ​*)serviceUUID characteristicUUID:(CBUUID *​)characteristicUUID p:(CBPeripheral ​*)p data:(NSData *​)data
    {
       CBService *service = [self findServiceFromUUID:serviceUUID p:p];

       if (!service)
       {
           NSLog(@"Could not find service with UUID %@ on peripheral with UUID %@",
                 [self CBUUIDToString:serviceUUID],
                 p.identifier.UUIDString);

           return;
       }

       CBCharacteristic *characteristic = [self findCharacteristicFromUUID:characteristicUUID service:service];

       if (!characteristic)
       {
           NSLog(@"Could not find characteristic with UUID %@ on service with UUID %@ on peripheral with UUID %@",
                 [self CBUUIDToString:characteristicUUID],
                 [self CBUUIDToString:serviceUUID],
                 p.identifier.UUIDString);

           return;
       }

       [p writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }

    - (void)peripheral:(CBPeripheral ​*)peripheral didWriteValueForCharacteristic:(CBCharacteristic *​)characteristic error:(NSError *)error
    {
       [[self delegate]bleDidSendData:error];
    }

但每次我都会收到以下错误。但我的消息发送成功    Error Domain=CBErrorDomain Code=0 "Unknown error." UserInfo=0x170070380 {NSLocalizedDescription=Unknown error.}

1 个答案:

答案 0 :(得分:0)

你可以这样做:

 - (void)peripheral:(CBPeripheral *)peripheral
    didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
                 error:(NSError *)error {
             if (error == nil) {
    if ([UIAlertController class])
    {

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert title" message:@"Alert message" preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:ok];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    else
    {

        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert title" message:@"Alert message" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];

    }
}
else {
    NSLog(@"Error writing characteristic %@",error);
}

}