ios - CBPeripheralManager 未上电

标签 ios iphone xcode bluetooth core-bluetooth

我一直收到一个错误,说我的 CBPeripheralManager 没有开机,但在我的代码中我觉得我执行了这个。这是我的代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Start up the CBPeripheralManager
    _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
    // Start up the CBCentralManager

    // And somewhere to store the incoming data
    _data = [[NSMutableData alloc] init];
}

/** Required protocol method.  A full app should take care of all the possible states,
 *  but we're just waiting for  to know when the CBPeripheralManager is ready
 */
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {

    if (peripheral.state == CBPeripheralManagerStatePoweredOn) {

        // We're in CBPeripheralManagerStatePoweredOn state...
        NSLog(@"self.peripheralManager powered on.");

        // ... so build our service.

        // Then the service
        CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID] primary:YES];

        // And add it to the peripheral manager
        [self.peripheralManager addService:transferService];
    }
}

然后我调用我的外围设备开始使用 IBAction 按钮做广告:

- (IBAction)advertise:(id)sender {
    [self.peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] }];
    [self.peripheralManager startAdvertising:@{ CBAdvertisementDataTxPowerLevelKey : @(YES)}];
}

最佳答案

您需要将对 CBPeripheralManager 的所有调用包装在状态检查中,以防止出现这些警告。由于您稍后只是在不确定的时间调用广告,因此您需要确保您的 peripheralManager 仍然通电并准备就绪。

- (IBAction)advertise:(id)sender
{
  if(self.peripheralManager.state == CBPeripheralManagerStatePoweredOn)
  {
    //Now you can call advertise
  }
}

关于ios - CBPeripheralManager 未上电,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20601927/

相关文章:

ios - 应用程序可以知道用户何时从 iOS 11 驾驶时驾驶请勿打扰功能吗?

ios - ITMS-90086 "Missing 64-bit support"将 Adob​​e Air 应用程序上传到 iTunes Connect 时出错

iphone - Cocos2d iOS : Why doesn't my CCMenuItemImage respond to touch events?

iphone - 自定义 UISearchDisplayController

ios - 如何在 xcode 8.3.2 中查看下载的配置文件?

ios - 从外部类向 UIButton 添加目标

ios - Facebook SDK v4和Parse SDK

iphone - 调用具有多个 subview 层次结构的协议(protocol)方法

ios - 聚焦时如何修复 UISearchController 搜索栏调整大小?

ios - 如何在同一相册的 Facebook 和 Twitter 上使用 SLComposeViewController 发布多张图片