关于蓝牙的恢复连接(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一點不懂的童鞋,只是闡述了大致的思路,和一點容易迷惑的地方。
總結
以上是生活随笔為你收集整理的关于蓝牙的恢复连接(Retrieve问题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PXE+kickstart网络安装Cen
- 下一篇: U_boot 的 bootcmd 和bo