【发布时间】:2016-08-21 14:52:48
【问题描述】:
我正在尝试跟踪是否在 iOS 设备上连接了蓝牙设备。我使用了以下代码:
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@interface scDeviceManager:NSObject <CBCentralManagerDelegate>
@property (nonatomic, strong) CBCentralManager *centralManager;
+ (scDeviceManager *) sharedInstance;
@end
#import "scDeviceManager.h"
@implementation scDeviceManager
@synthesize centralManager = _centralManager;
+ (scDeviceManager *) sharedInstance {
static scDeviceManager *_sharedInstance=nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
- (id)init {
if (self = [super init]) { // equivalent to "self does not equal nil"
_centralManager=[[CBCentralManager alloc] initWithDelegate:self queue:nil];
//also tried
//_centralManager=[[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
return self;
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"Peripheral connected");
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
_log=[[Logger alloc] initWithClassName:NSStringFromClass([self class])];
switch (central.state) {
case CBCentralManagerStatePoweredOff:
NSLog(@"CoreBluetooth BLE hardware is powered off.");
break;
case CBCentralManagerStatePoweredOn:
NSLog(@"CoreBluetooth BLE hardware is powered on and ready.");
[_centralManager scanForPeripheralsWithServices:nil options:nil];
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:
NSLog([NSString stringWithFormat:@"Nothing to do: state (%ld).",(long)central.state]);
break;
}
}
@end;
在某些时候,我将对象称为 scDeviceManager:
scDeviceManager *deviceManager = [scDeviceManager sharedInstance];
当我从 iOS 激活/停用蓝牙时,我会收到以下消息:
2016-04-27 13:33:21.940 CoreBluetooth BLE 硬件已断电。
2016-04-27 13:33:24.046 CoreBluetooth BLE 硬件已开机并且 准备好了。
这表示蓝牙已激活,我正在扫描新的蓝牙设备。
但是,当我连接蓝牙设备(三星 HM1700、蓝牙耳机)时,不会调用 didConnectPeripheral。确保蓝牙设备已连接,因为我可以听音乐。
在自定义 iOS 按钮中,我调用以下函数
-(void) scanConnectedDevices{
NSArray *inputs = [[AVAudioSession sharedInstance] availableInputs];
for (AVAudioSessionPortDescription *port in inputs)
{
connectedAudioDevices[port.portType]=port;
NSLog(@"type:%@, name:%@",port.portyType,port.portName)
}
}
我得到的是:
MicrophoneBuiltIn:iPhone 麦克风
蓝牙HFP:HM1700
这表示设备已连接。但是,每当我连接/断开蓝牙设备时,我希望通过一个委托来执行代码和平。
谢谢
【问题讨论】:
-
CoreBluetooth 仅适用于低功耗蓝牙,三星 HM1700 不是低功耗蓝牙设备。
-
Ic...是否可以为蓝牙耳机委托代理?
标签: ios objective-c delegates ios-bluetooth