How to get the status of bluetooth (ON/OFF) in iphone programmatically

A little bit of research into Sam’s answer that I thought I’d share
You can do so without utilizing private API, but with a few caveats:

  • It will only work on iOS 5.0+
  • It will only work on devices that
    support the bluetooth LE spec (iPhone 4S+, 5th Generation iPod+, iPad
    3rd Generation+)
  • Simply allocating the class will cause your application to ask permission to use the bluetooth stack from the user (may not be desired), and if they refuse, the only thing you’ll see is CBCentralManagerStateUnauthorized iOS7+ Revision: Aforementioned strike-through can now be prevented, see comments below which point to this answer which explains you can set CoreBluetooth’s CBCentralManagerOptionShowPowerAlertKey option to NO to prevent permissions prompt.
  • Retrieval of bluetooth state is async, and continuous. You will need to setup a delegate to get state changes, as checking the state of a freshly allocated bluetooth manager will return CBCentralManagerStateUnknown

That being said, this method does seem to provide real time updates of bluetooth stack state.

After including the CoreBluetooth framework,

#import <CoreBluetooth/CoreBluetooth.h>

These tests were easy to perform using:

- (void)detectBluetooth
{
    if(!self.bluetoothManager)
    {
        // Put on main queue so we can call UIAlertView from delegate callbacks.
        self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
    }
    [self centralManagerDidUpdateState:self.bluetoothManager]; // Show initial state
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString *stateString = nil;
    switch(self.bluetoothManager.state)
    {
        case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break;
        case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy."; break;
        case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy."; break;
        case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off."; break;
        case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use."; break;
        default: stateString = @"State unknown, update imminent."; break;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bluetooth state"
                                                     message:stateString
                                                    delegate:nil
                                          cancelButtonTitle:@"ok" otherButtonTitles: nil];
    [alert show];
}

Leave a Comment