关于蓝牙的恢复连接(Retrieve问题)

在iOS中蓝牙恢复连接有三种方式,这里主要讲解其中一种:与在过去的一段时间连接的过的设备重新连接。
基本思路:
1、当程序退出时,将已连接设备的identifier(NSUUID)保存。
2、在程序恢复的时候,通过已保存的identifier查找周边是否有这个设备。
3、如果有,则尝试重新连接这个设备。
 
具体实现步骤:
1、当程序退出时,将已连接设备的identifier(NSUUID)保存
     通过AppDelegate中的 - (void)applicationWillTerminate:(UIApplication *)application;回调函数可以抓取到程序退出的动作,在这个回调函数中实现identifier保存的操作。如下
 
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[SHZCentralManager sharedInstance] SHZSaveKnownPeripherals];
}
 
- (void)SHZSaveKnownPeripherals{
    knownPeripherals = [myPeripheral identifier];
    NSString *identifer = knownPeripherals.UUIDString;
    [self saveKnowPeripheralIdentifer:identifer];
}
 
2、在程序恢复的时候,通过已保存的identifier查找周边是否有这个设备。
当程序加载后,可以选择合适的机会进行已知设备的重连,之前需要通过ios的标准API进行已知设备的查找,确定这个设备是在周围的。
我会选择在 centralManagerDidUpdateState中进行设备的重连操作,如下:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    NSLog(@"SHZCentralManager centralManagerDidUpdateState");
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            NSLog(@"CBCentralManagerStatePoweredOn");
            [self SHZRetrieveKnownPeripherals];
            break;
        default:
            break;
    }
}
之后调用:SHZRetrieveKnownPeripherals函数,进行重连,如下
- (void)SHZRetrieveKnownPeripherals{
    NSArray *knownPeripheralsIdentifiers = [self readKnowPeripheralIdentifers];
    if (knownPeripheralsIdentifiers != nil) {
        NSArray *peripherals = [myCentralManager retrievePeripheralsWithIdentifiers:knownPeripheralsIdentifiers];
        for (CBPeripheral *peripheral in peripherals) {
            [self addContentToScreenLogTextView:[NSString stringWithFormat:@"Try to reconnect peripheral %@", peripheral]];
            myPeripheral = peripheral;
            myPeripheral.delegate = self;
            [self connectPeripheral:peripheral];
        }
    }
}
这个函数的基本思路是,读取保存的identifier,通过retrievePeripheralsWithIdentifiers:knownPeripheralsIdentifiers来返回一个可以重连的peripherals的列表(而不是通过didRetrievePeripherals:回调函数进行后续操作,这里让我卡住了很久,最后发现原来被耍了),然后对这个列表进行遍历,尝试与每一个Peripheral进行连接,之后的操作与一般的连接操作相同。
上面的readKnowPeripheralIdentifers函数如下:
- (NSArray*)readKnowPeripheralIdentifers{
    NSString *identifer = [[NSUserDefaults standardUserDefaults] stringForKey:ConstantsKnowPeripheralIdentifer];
    if (identifer == nil) {
        return nil;
    }
    NSUUID *res = [[NSUUID alloc] initWithUUIDString:identifer];
   
    return @[res];
connectPeripheral:peripheral函数如下:
- (void)connectPeripheral:(CBPeripheral*)peripheral{
    [myCentralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey: @YES}];
}
注意几点:
1、不要被 didRetrievePeripherals函数迷惑,它其实在这里没有用的。
2、在得到Peripheral后,请先设备他的代理,再进行连接操作,否则后续操作获取不到。
3、上述过程省略了很多细节,不适合对CoreBluetooth一点不懂的童鞋,只是阐述了大致的思路,和一点容易迷惑的地方。
原文地址:https://www.cnblogs.com/scaptain/p/4528230.html