大致了解了coreBluetooth后,接下来开始着手建立连接的事情。连接大致分为以下几个步骤。
重要提示!!!Xcode10 之后,扫描外设出来的值,会变成 <length=8 byte=0x00000000> 类似这样的!!! 这会导致,原来的mac 扫描识别,直接取值出现问题。请自行转换!
- 根据自己的需求,确定是否创建一个蓝牙管理的单例类,个人建议是最好使用蓝牙管理的单例类,这样其他地方调用也方便一点。
- 初始化CBCentralManager,初始化之后,记得设置代理。
- (instancetype)initWithDelegate:(nullable id<CBCentralManagerDelegate>)delegate queue:(nullable dispatch_queue_t)queue options:(nullable NSDictionary<NSString *, id> *)options NS_AVAILABLE(10_9, 7_0) NS_DESIGNATED_INITIALIZER;
其中需要注意:options的参数,参数有很多,举例说两个,其他的参考API
/*! * @const CBCentralManagerOptionShowPowerAlertKey * * @discussion An NSNumber (Boolean) indicating that the system should, if Bluetooth is powered off when <code>CBCentralManager</code> is instantiated, display * a warning dialog to the user. * * @see initWithDelegate:queue:options: * */ CB_EXTERN NSString * const CBCentralManagerOptionShowPowerAlertKey NS_AVAILABLE(10_9, 7_0);
大致意思是说,如果是给的YES,那么在初始化CBCentralManager的时候,如果蓝牙没有打开,那么会以alert的形式提示用户打开蓝牙,但是似乎,iOS11以后就不太好用了。
/*! * @const CBCentralManagerOptionRestoreIdentifierKey * * @discussion An NSString containing a unique identifier (UID) for the <code>CBCentralManager</code> that is being instantiated. This UID is used * by the system to identify a specific <code>CBCentralManager</code> instance for restoration and, therefore, must remain the same for * subsequent application executions in order for the manager to be restored. * * @see initWithDelegate:queue:options: * @seealso centralManager:willRestoreState: * */ CB_EXTERN NSString * const CBCentralManagerOptionRestoreIdentifierKey NS_AVAILABLE(10_13, 7_0);
个人理解,就是将你初始化的这个CBCentralManager存储到系统蓝牙队列里面,如果你的程序gg以后,当系统蓝牙唤醒你的app以后会通过 cen