8

我有两个应用程序,一个作为外围设备(在 iPad 4th Gen 上运行 iOS 7),一个作为中央应用程序(iPhone 5c 运行 iOS7)。

我希望在外围设备中有一个可写的特性,中央写入少量字节(大约 4 个字节,但可能因执行而异)。

我正在配置外围设备如下:

-(void)startPeripheral
{
    CBMutableService *service = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:kMyServiceUUID] primary:YES];
    CBMutableCharacteristic *ch = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:kMyWriteUUID] properties:CBCharacteristicPropertyWrite value:nil permissions:CBAttributePermissionsWriteable];
    service.characteristics = @[ch];

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@[[CBUUID UUIDWithString:kMyServiceUUID]], CBAdvertisementDataServiceUUIDsKey, @"My Peripheral", CBAdvertisementDataLocalNameKey, nil];

    [self.peripheralManager addService:service];
    [self.peripheralManager startAdvertising:dict];

    NSLog(@"Service = %@",service);
}

起初这一切似乎都有效,外围设备发布服务,我的中心可以扫描,查找,发现服务和特性并找到它感兴趣的特性。当我尝试写入特性时问题就来了。

在中央我有以下方法:

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"Service/Characteristics = %@",service.characteristics);
    for(CBCharacteristic *ch in service.characteristics)
    {
        NSLog(@"Characteristic properties = %x",ch.properties);
        NSLog(@"Characterisctic = %@",ch.UUID);
        if([ch.UUID isEqual:[CBUUID UUIDWithString:kMyWriteUUID]])
        {
            // We've found our write characteristic
            NSLog(@"Writing data to characteristic %@",ch.UUID);
            NSData *data = [NSData dataWithBytes:(Byte[]){1,2,3,4} length:4];
            [peripheral writeValue:data forCharacteristic:ch type:CBCharacteristicWriteWithResponse];
        }
    }
 }

我收到一个回调到 didWriteValueForCharacteristic,它指示错误:

错误域=CBATTErrorDomain 代码=14“不太可能的错误。”

这不是很有帮助。

任何人都可以发现问题或提出任何解决方案吗?

谢谢,丰富

4

3 回答 3

0

尝试在收到以下回调之前不要添加您的服务:

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral

然后检查外围设备的状态以获取 CBPeripheralManagerStatePoweredOn。外设未开机时添加服务无效。

于 2014-01-29T19:11:41.393 回答
0

对我来说,错误是什么并不明显,但是:

  1. peripheralManager:didAddService:error:您应该在收到回调后才开始投放广告。
  2. 你能附上相应的设备控制台日志吗?(使用管理器->电话->控制台)
于 2013-11-10T10:45:44.560 回答
0

当我在外围设备端输错委托时,我遇到了同样的错误,请仔细检查实现的委托签名

我写过

-(void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequest:(NSArray *)requests

代替

-(void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests

(见第一个版本中缺少的's')

于 2015-08-11T08:28:52.757 回答