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

I trying to get the Status of iPhone/iPod Bluetooth that whether it is ON or OFF programmatically.
Is it possible using some Apple API or third party API.

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

To disable the default alert message you just need to pass through an option dictionary when you instantiate the CBPeripheralManager:
SWIFT tested on iOS8+
import CoreBluetooth
//Define class variable in your VC/AppDelegate
var bluetoothPeripheralManager: CBPeripheralManager?
//On viewDidLoad/didFinishLaunchingWithOptions
let options = [CBCentralManagerOptionShowPowerAlertKey:0] //<-this is the magic bit!
bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options)
Obviously you also need to implement the CKManagerDelegate delegate method peripheralManagerDidUpdateState as outlined above as well:
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {
var statusMessage = ""
switch peripheral.state {
case .poweredOn:
statusMessage = "Bluetooth Status: Turned On"
case .poweredOff:
statusMessage = "Bluetooth Status: Turned Off"
case .resetting:
statusMessage = "Bluetooth Status: Resetting"
case .unauthorized:
statusMessage = "Bluetooth Status: Not Authorized"
case .unsupported:
statusMessage = "Bluetooth Status: Not Supported"
case .unknown:
statusMessage = "Bluetooth Status: Unknown"
}
print(statusMessage)
if peripheral.state == .poweredOff {
//TODO: Update this property in an App Manager class
}
}

This answer has been updated from the original Objective-C to Swift 4.0.
It is assumed that you have already created a bluetooth manager and assigned the delegate to the ViewController class.
import CoreBluetooth
extension ViewController : CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
print("powered on")
case .poweredOff:
print("powered off")
case .resetting:
print("resetting")
case .unauthorized:
print("unauthorized")
case .unsupported:
print("unsupported")
case .unknown:
print("unknown")
}
}
}

Some updates on BadPirate's answer, with iOS7 you can set the central manager not to show the alert when allocating the manager object by giving it a NSDictionary that has key "CBCentralManagerOptionShowPowerAlertKey" set to 0.
self.cbManager = [[CBCentralManager alloc] initWithDelegate:self
queue:nil
options:
[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0]
forKey:CBCentralManagerOptionShowPowerAlertKey]];

There is a way on iOS 5 and above using CoreBluetooth. The class you can use is CBCentralManager. It has a property 'state' that you can check to see if Bluetooth is on or not. (the enum CBCentralManagerState has the value(s) you want to check against).

Once you have the CBCentralManager setup you can use CBCentralManager::state and CBCentralManager::authorization either from a delegate method or directly.
import CoreBluetooth
class Manager {
let centralManager = CBCentralManager(delegate: self, queue: nil)
var isBTTurnedOn: Bool {
return centralManager.state == .poweredOn
}
var isAuthorized: Bool {
if #available(iOS 13.0, *) {
return centralManager.authorization == .allowedAlways
} else {
return true
}
}
}

This solution is bit old , before apple introducing core bluetooth
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
Class BluetoothManager = objc_getClass( "BluetoothManager" ) ;
id btCont = [BluetoothManager sharedInstance] ;
[self performSelector:#selector(status:) withObject:btCont afterDelay:1.0f] ;
return YES ;
}
- (void)status:(id)btCont
{
BOOL currentState = [btCont enabled] ;
//check the value of currentState
}

Related

iOS11 bluetooth has something strange

When I switch off the Bluetooth in setting, then I use CBCentralManager to get the state of the Bluetooth like this:
self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
the system will display a alert like this: system alert
The current state of Bluetooth is CBManagerStatePoweredOff. But when I switch off the Bluetooth in control center, this alert is not show anymore even if the current state of Bluetooth is still CBManagerStatePoweredOff.
How could I remind the user to switch on the Bluetooth in this situation?
You can remind the users by implementing the following delegate method.
//Bluetooth state delegation
#pragma mark - CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
NSString *stateString = nil;
switch(self.CBManager.state)
{
case CBManagerStateResetting:
stateString = #"The connection with the system service was momentarily lost, update imminent.";
break;
case CBManagerStateUnsupported:
stateString = #"The platform doesn't support Bluetooth Low Energy."; break;
case CBManagerStateUnauthorized: stateString = #"The app is not authorized to use Bluetooth Low Energy.";
break;
case CBManagerStatePoweredOff:
stateString = #"Bluetooth is currently powered off.";
break;
case CBManagerStatePoweredOn:
[self.beaconManager startMonitoringForRegion:self.museumsRegion];
[self.beaconManager startRangingBeaconsInRegion: self.museumsRegion];
break;
case CBManagerStateUnknown:
stateString = #"State unknown, update imminent.";
break;
}
NSLog(#"%#", stateString);
}
Now the user should be informed automatically.
You can disable system BlueTooth alert by using CBCentralManagerOptionShowPowerAlertKey in options dict.
NSDictionary *options = #{CBCentralManagerOptionShowPowerAlertKey: #NO};
self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
Then you can using deleget method centralManagerDidUpdateState: to popup you custom alert.

Continuously Showing "Turn on Bluetooth to allow app to connect to accessories" alert message in background in ios

I am using iBeacon Technology in my application. I'm checking in the app whether the bluetooth is enabled or disable by the user and for that i have written code below.
- (void)viewDidLoad
{
[super viewDidLoad];
_bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
}
// bluetooth manager state change
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
NSString *stateString = nil;
switch(central.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;
}
}
Problem : This above alert Message prompts very oftenly in background or when the other app is open even if i have kill the application. I want to show this default alert message but only when the user opens the app.
Can anyone provide me a solution?
self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self
queue:nil
options:#{CBCentralManagerOptionShowPowerAlertKey: #NO}];
This maybe works to hide the system pop up.

iOS8 and BTLE | CBCentralManager unable to find peripherals

I have an iOS app that is connecting to a device (arduino) using a BTLE. Everything is working fine on my iPad iOS 7. After upgrading to iOS 8, the CBCentralManager is not finding any peripherals.
- (void)startScanningForSupportedUUIDs
{
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
}
I don't know what can be the problem.
I have the solution, for some reason in iOS 8 there is some delay after instantiate your CBManager. You need to start to scan when the CBCentralManager is on, in this method:
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state) {
case CBCentralManagerStatePoweredOff:
NSLog(#"CoreBluetooth BLE hardware is powered off");
break;
case CBCentralManagerStatePoweredOn:
{
NSLog(#"CoreBluetooth BLE hardware is powered on and ready");
NSArray *uuidArray = [NSArray arrayWithObjects:[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID], nil];
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
[centralManager scanForPeripheralsWithServices:uuidArray options:options];
}
break;
case CBCentralManagerStateResetting:
NSLog(#"CoreBluetooth BLE hardware is resetting");
break;
case CBCentralManagerStateUnauthorized:
NSLog(#"CoreBluetooth BLE state is unauthorized");
break;
case CBCentralManagerStateUnknown:
NSLog(#"CoreBluetooth BLE state is unknown");
break;
case CBCentralManagerStateUnsupported:
NSLog(#"CoreBluetooth BLE hardware is unsupported on this platform");
break;
default:
break;
}
In IOS 7 you could get away by starting a BLE scan even before the CBCentralManager was ready. IOS 7 used to spit out a warning in such cases -
CoreBluetooth[API MISUSE] can only accept commands while in the powered on state
With IOS8 - the warning no more appears and the scan does not actually start. To overcome the problem, wait for the CBCentral to power on - ie, wait for CBCentral manager to get to the "CBCentralManagerStatePoweredOn" state and then start the scan. It works fine with that change:)

Detect (listen to) audio route change in iOS 7

Just starting development for iOS 7, and found that AudioSession related functions and PropertyListeners are deprecated in iOS 7.
Before I use the following method to detect if a headset has been plugged in or unplugged from the device:
/* add callback for device route change */
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
(__bridge void *)(self));
Then implement the listener callback to do different things to the internal algorithms. Now iOS 7 deprecated it and there's no documentations on any alternative, Is there any solutions by experts here? Thanks!
Handle the notification AVAudioSessionRouteChangeNotification (Available in iOS 6.0 and later.)
Try this code for Swift 4.2 :
#objc func handleRouteChange(_ notification: Notification) {
let reasonValue = (notification as NSNotification).userInfo![AVAudioSessionRouteChangeReasonKey] as! UInt
let routeDescription = (notification as NSNotification).userInfo![AVAudioSessionRouteChangePreviousRouteKey] as! AVAudioSessionRouteDescription?
NSLog("Route change:")
if let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) {
switch reason {
case .newDeviceAvailable:
NSLog(" NewDeviceAvailable")
case .oldDeviceUnavailable:
NSLog(" OldDeviceUnavailable")
case .categoryChange:
NSLog(" CategoryChange")
NSLog(" New Category: %#", AVAudioSession.sharedInstance().category.rawValue)
case .override:
NSLog(" Override")
case .wakeFromSleep:
NSLog(" WakeFromSleep")
case .noSuitableRouteForCategory:
NSLog(" NoSuitableRouteForCategory")
case .routeConfigurationChange:
NSLog(" RouteConfigurationChange")
case .unknown:
NSLog(" Unknown")
#unknown default:
NSLog(" UnknownDefault(%zu)", reasonValue)
}
} else {
NSLog(" ReasonUnknown(%zu)", reasonValue)
}
if let prevRout = routeDescription {
NSLog("Previous route:\n")
NSLog("%#", prevRout)
NSLog("Current route:\n")
NSLog("%#\n", AVAudioSession.sharedInstance().currentRoute)
}
}
And use it in func setupAudioSession()
private func setupAudioSession() {
// Configure the audio session
let sessionInstance = AVAudioSession.sharedInstance()
// we don't do anything special in the route change notification
NotificationCenter.default.addObserver(self,
selector: #selector(self.handleRouteChange(_:)),
name: AVAudioSession.routeChangeNotification,
object: sessionInstance)
}
For Objective C try this code
- (void)handleRouteChange:(NSNotification *)notification
{
UInt8 reasonValue = [[notification.userInfo valueForKey:AVAudioSessionRouteChangeReasonKey] intValue];
AVAudioSessionRouteDescription *routeDescription = [notification.userInfo valueForKey:AVAudioSessionRouteChangePreviousRouteKey];
NSLog(#"Route change:");
switch (reasonValue) {
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
NSLog(#" NewDeviceAvailable");
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
NSLog(#" OldDeviceUnavailable");
break;
case AVAudioSessionRouteChangeReasonCategoryChange:
NSLog(#" CategoryChange");
NSLog(#" New Category: %#", [[AVAudioSession sharedInstance] category]);
break;
case AVAudioSessionRouteChangeReasonOverride:
NSLog(#" Override");
break;
case AVAudioSessionRouteChangeReasonWakeFromSleep:
NSLog(#" WakeFromSleep");
break;
case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory:
NSLog(#" NoSuitableRouteForCategory");
break;
default:
NSLog(#" ReasonUnknown");
}
NSLog(#"Previous route:\n");
NSLog(#"%#\n", routeDescription);
NSLog(#"Current route:\n");
NSLog(#"%#\n", [AVAudioSession sharedInstance].currentRoute);
}
And use it in (void)setupAudioSession
- (void)setupAudioSession {
// Configure the audio session
AVAudioSession *sessionInstance = [AVAudioSession sharedInstance];
// we don't do anything special in the route change notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(handleRouteChange:)
name:AVAudioSessionRouteChangeNotification
object:sessionInstance];
}

iOS - check if bluetooth is on without system alert popup to user

This code allows to determine current bluetooth status:
CBCentralManager* testBluetooth = [[CBCentralManager alloc] initWithDelegate:nil queue: nil];
switch ([testBluetooth state]) {....}
But, when [[CBCentralManager alloc] init...] happens, system popups an alert to user, if bluetooth is off.
Is there any way to check bluetooth status without disturbing my users?
I got the following response from an apple developer : In iOS7, the CBCentralManagerOptionShowPowerAlertKey option lets you disable this alert.
If you havea a CBCentralManager when you initialise it, you can use the method initWithDelegate:queue:options
Example:
In my .h file i have a CBCentralManager * manager
In .m file :
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], CBCentralManagerOptionShowPowerAlertKey, nil];
_manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
[_manager scanForPeripheralsWithServices:nil options:nil];
With this code the warning no longer appears, I hope that helps !
In swift you can do write these two lines in your app delegate inside the func: didFinishLaunchingWithOptions launchOptions
self.bCentralManger = CBCentralManager(delegate: self, queue: dispatch_get_main_queue(), options: [CBCentralManagerOptionShowPowerAlertKey: false])
self.bCentralManger.scanForPeripheralsWithServices(nil, options: nil)
where your bCentralManger should be declared as :
private var bCentralManger: CBCentralManager!
I have used below code to disable alert for iOS 8 and above version
self.bluetoothManager = [[CBCentralManager alloc]
initWithDelegate:self
queue:dispatch_get_main_queue()
options:#{CBCentralManagerOptionShowPowerAlertKey: #(NO)}];
[self.bluetoothManager scanForPeripheralsWithServices:nil options:nil];
By combining on BadPirate's and Anas' answer, you can get the bluetooth state without show system alert.
#import <CoreBluetooth/CoreBluetooth.h>
#interface ShopVC () <CBCentralManagerDelegate>
#property (nonatomic, strong) CBCentralManager *bluetoothManager;
#end
#implementation ShopVC
- (void)viewDidLoad {
[super viewDidLoad];
if(!self.bluetoothManager)
{
NSDictionary *options = #{CBCentralManagerOptionShowPowerAlertKey: #NO};
self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
}
}
#pragma mark - CBCentralManagerDelegate
- (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];
}
I've only tested this on iOS 9 so maybe someone could test this one older OS devices.
We do everything normally except one thing, instead of settings the CBCentralManager Delegate in viewDidLoad we leave this until the moment we need it, in the example case below I call this once my WKWebView has finished loading, and because each page of my web view potentially requires the use of Bluetooth I put this in WKWebView didFinishNavigation.
Swift
var managerBLE: CBCentralManager?
func bluetoothStatus() {
managerBLE = CBCentralManager(delegate: self, queue: nil, options: nil)
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
bluetoothStatus()
}
func centralManagerDidUpdateState(central: CBCentralManager) {
switch managerBLE!.state
{
case CBCentralManagerState.PoweredOff:
print("Powered Off")
case CBCentralManagerState.PoweredOn:
print("Powered On")
case CBCentralManagerState.Unsupported:
print("Unsupported")
case CBCentralManagerState.Resetting:
print("Resetting")
fallthrough
case CBCentralManagerState.Unauthorized:
print("Unauthorized")
case CBCentralManagerState.Unknown:
print("Unknown")
default:
break;
}
}
The moment that delegate is set within bluetoothStatus() you will see the state change fire.
The notification to turn on Bluetooth only seems to want to be called right at the initial load of your app, doing it this way mean you just get what you want from the centralManagerDidUpdateState
There is currently no way to disable this alert when your application is run on a iOS device which supports Bluetooth LE and where Bluetooth is disabled. It would be an enhancement request to provide a means to disable the alert. So the more requests Apple gets about this enhancement, the better.

Resources