如何在我的应用启动时自动打开蓝牙连接

时间:2016-03-11 05:19:24

标签: ios objective-c iphone

我正在开发能够识别ibeacons并执行预定义动作的应用程序,我想要做的是当我的应用程序启动时蓝牙将自动“开启”。如果在iPhone中可以,我该怎么办?

2 个答案:

答案 0 :(得分:1)

抱歉,您不能以编程方式执行此操作,至少不能使用iOS。也许您可以选择检测设备蓝牙的状态。在此基础上,您可以为应用设置启用/禁用条件。

以下是如何在您的应用中检测蓝牙状态:

我建议你简单一点,创建一个子类化为NSObject的模型类。

  

然后把它变成单吨课程,

#import <CoreBluetooth/CoreBluetooth.h>
  

添加属性

@property (nonatomic, strong) CBCentralManager *bluetoothManager;
  

在班级中指派一名代表

YourClass<CBCentralManagerDelegate>
  

添加init这样的方法,

- (instancetype) init {
    self = [super init];
    if(self) {
        self.bluetoothManager = [[CBCentralManager alloc]
                                 initWithDelegate:self
                                 queue:dispatch_get_main_queue()
                                 options:@{CBCentralManagerOptionShowPowerAlertKey: @(NO)}];
    }
    return self;
}
  

添加此委托方法以获取蓝牙的状态

- (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;
    }
    NSLog(@"Bluetooth State: %@",stateString);
}
  

主要非常重要:您需要为项目启用以下功能。

enter image description here

答案 1 :(得分:0)

在项目

中添加此项

http://iphone-dev.googlecode.com/svn/branches/include-1.2-sdk/include/BluetoothManager/

#import <BluetoothManager/BluetoothManager.h>

要启用蓝牙,请输入以下代码:

BluetoothManager *manager = [BluetoothManager sharedInstance];
[manager setEnabled:YES];