Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CBPeripheralManager is not powered on

I keep getting an error saying my CBPeripheralManager is not powered on but in my code i feel that i carried this out. Here is my code:

- (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];
    }
}

Then later I call my peripheral to start advertising with an IBAction button:

- (IBAction)advertise:(id)sender {
    [self.peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] }];
    [self.peripheralManager startAdvertising:@{ CBAdvertisementDataTxPowerLevelKey : @(YES)}];
}
like image 474
ian Avatar asked Dec 16 '13 00:12

ian


1 Answers

You need to wrap all your calls to the CBPeripheralManager inside a state check in order to prevent these warnings. Since you are just calling advertise at an undetermined time later, you need to ensure your peripheralManager is still powered and ready to go.

- (IBAction)advertise:(id)sender
{
  if(self.peripheralManager.state == CBPeripheralManagerStatePoweredOn)
  {
    //Now you can call advertise
  }
}
like image 61
Tommy Devoy Avatar answered Oct 01 '22 14:10

Tommy Devoy