在做藍(lán)牙連接開發(fā)的時候遇到一個問題团甲,就是在iOS連接完藍(lán)牙后镐确,再運(yùn)行其它程序,有時就會出現(xiàn)因系統(tǒng)內(nèi)存不足被結(jié)束連接锥余,這種情況就會影響使用腹纳,所以為了解決這個查看了很多資料,終于解決了驱犹。
這個是iOS特有的一個解決方法嘲恍,Core Bluetooth State Preservation and Restoration,就是在被終結(jié)的時候會把連接的藍(lán)牙信息存儲起來雄驹,以后會根據(jù)這個來恢復(fù)連接佃牛。
需要改動的地方有這幾個:
1.初始化藍(lán)牙管理
centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey : restoreIdentifier])
你需要在初始化的時候設(shè)定特定需要恢復(fù)連接的藍(lán)牙標(biāo)示restoreIdentifier,在恢復(fù)的時候會用到医舆。
2.啟動的時候恢復(fù)藍(lán)牙
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { ? ? ? ?
if let launchOptions = launchOptions {? // 2? if let centralManagerUUIDs = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey] as? Array{
for id in centralManagerUUIDs {
if id == Device.centralRestoreIdentifier {
// Restore the CBCentralManager here
}
}
}
}
return true
}
3.觸發(fā)恢復(fù)藍(lán)牙的時候的操作
func centralManager(central: CBCentralManager, willRestoreState dict: [String : AnyObject]) {? ? // 1? if let peripheralsObject = dict[CBCentralManagerRestoredStatePeripheralsKey] {? ? // 2? ? let peripherals = peripheralsObject as! Array// 3
if peripherals.count > 0 {
// 4
peripheral = peripherals[0]
// 5
peripheral?.delegate = self
}
}
}
4.另外俘侠,為了確保藍(lán)牙已連接,可以在更新狀態(tài)的時候判斷下蔬将,如果沒有連接成功爷速,再次開啟掃描連接。
參考的資料:
https://www.cloudcity.io/blog/2016/09/14/zero-to-ble-on-ios--part-three/
https://news.realm.io/news/altconf-shuichi-tsutsumi-practical-core-bluetooth/