如何以编程方式获取iphone中蓝牙(ON/OFF)的状态

Nil*_*ikh 39 iphone bluetooth iobluetooth ios

我试图通过编程方式获取iPhone/iPod蓝牙的状态,无论是开启还是关闭.是否可以使用某些Apple API或第三方API.

Bad*_*ate 48

Sam的答案进行了一些研究,我认为我会分享你可以在不使用私有API的情况下这样做,但有几点需要注意:

  • 它只适用于iOS 5.0+
  • 它仅适用于支持蓝牙LE规格的设备(iPhone 4S +,第5代iPod +,iPad第3代+)
  • 简单地分配类将导致您的应用程序请求允许使用来自用户的蓝牙堆栈(可能不需要),如果他们拒绝,您唯一能看到的是CBCentralManagerStateUnauthorized iOS7 + Revision:前面提到的罢工现在可以防止,请参阅下面的评论指出这个答案解释了你可以将CoreBluetooth的CBCentralManagerOptionShowPowerAlertKey选项设置为NO以防止权限提示.
  • 蓝牙状态的检索是异步的,并且是连续的.您将需要设置委托来获取状态更改,因为检查新分配的蓝牙管理器的状态将返回CBCentralManagerStateUnknown

话虽这么说,这种方法似乎确实提供了蓝牙堆栈状态的实时更新.

包含CoreBluetooth框架后,

#import <CoreBluetooth/CoreBluetooth.h>
Run Code Online (Sandbox Code Playgroud)

这些测试很容易使用:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

  • 你提到了隐含的,但为了保持一致性:声明属性`@property(nonatomic,strong)CBCentralManager*bluetoothManager;`并设置你的类符合协议`CBCentralManagerDelegate` (2认同)
  • 您可以使用CBCentralManager上的指定初始化程序来避免警报消息,请查看以下答案:http://stackoverflow.com/a/19367494/823483 (2认同)

小智 24

要禁用默认警报消息,只需在实例化CBPeripheralManager时通过选项字典:

SWIFT在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)
Run Code Online (Sandbox Code Playgroud)

显然,您还需要实现上面概述的CKManagerDelegate委托方法peripheralManagerDidUpdateState:

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
    }
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*der 11

这个答案已经从最初的Objective-C更新到Swift 4.0.

假设您已经创建了一个蓝牙管理器并将该委托分配给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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

在BadPirate的回答有些更新与iOS7您可以通过给它拥有关键的"CBCentralManagerOptionShowPowerAlertKey"设置为0的NSDictionary分配管理对象时设置的中央管理器不显示警报.

self.cbManager = [[CBCentralManager alloc] initWithDelegate:self
                                                          queue:nil
                                                        options:
                      [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0]
                                                  forKey:CBCentralManagerOptionShowPowerAlertKey]];
Run Code Online (Sandbox Code Playgroud)


Raj*_*Raj 0

这个解决方案有点老了,在苹果推出核心蓝牙之前

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

    }
Run Code Online (Sandbox Code Playgroud)