sonido recuperar porque por equipo encuentra eliminado dispositivos dispositivo configurar conectar conecta como ios iphone bluetooth iobluetooth

ios - recuperar - Cómo obtener el estado de bluetooth(ON/OFF) en el iPhone mediante programación



configurar bluetooth iphone 6 (6)

Algunas actualizaciones sobre la respuesta de BadPirate, con iOS7 puede configurar el administrador central para que no muestre la alerta al asignar el objeto administrador dándole un NSDictionary que tenga la clave "CBCentralManagerOptionShowPowerAlertKey" puesta a 0.

self.cbManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options: [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:CBCentralManagerOptionShowPowerAlertKey]];

Estoy tratando de obtener el estado del iPhone / iPod Bluetooth, ya sea que esté activado o desactivado mediante programación. ¿Es posible usar alguna API de Apple o una API de terceros?


Esta respuesta se ha actualizado desde Objective-C original a Swift 4.0.

Se supone que ya ha creado un gestor de bluetooth y le ha asignado el delegado a la clase ViewController .

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") } } }


Esta solución es un poco vieja, antes de que Apple introduzca el núcleo 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 }


Hay una forma en iOS 5 y superior usando CoreBluetooth. La clase que puede usar es CBCentralManager. Tiene un ''estado'' de propiedad que puede verificar para ver si Bluetooth está activado o no. (la enumeración CBCentralManagerState tiene el valor (es) con el que desea verificar).


Para deshabilitar el mensaje de alerta predeterminado solo necesita pasar a través de un diccionario de opciones cuando crea una instancia del CBPeripheralManager:

SWIFT probado en 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)

Obviamente, también necesita implementar el método de delegado CKManagerDelegate peripheralManagerDidUpdateState como se describe anteriormente:

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


Un poco de investigación sobre la respuesta de Sam que pensé que podría compartir. Puede hacerlo sin utilizar una API privada, pero con algunas advertencias:

  • Solo funcionará en iOS 5.0+
  • Solo funcionará en dispositivos compatibles con la especificación LE bluetooth (iPhone 4S +, iPod 5ta generación, iPad 3ra generación +)
  • Simplemente asignar la clase hará que su aplicación pida permiso para usar la pila bluetooth del usuario (puede que no se desee), y si se niegan, lo único que verán es CBCentralManagerStateUnauthorized
  • La recuperación del estado de bluetooth es asincrónica y continua. Tendrá que configurar un delegado para obtener cambios de estado, ya que al comprobar el estado de un gestor de bluetooth recién asignado, se devolverá CBCentralManagerStateUnknown.

Dicho esto, este método parece proporcionar actualizaciones en tiempo real del estado de pila bluetooth.

Después de incluir el marco CoreBluetooth,

#import <CoreBluetooth/CoreBluetooth.h>

Estas pruebas fueron fáciles de realizar usando:

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