Re-connect bluetooth device when app is terminated by user

廉价感情. 提交于 2019-11-28 08:30:48

问题


I have a bluetooth device with a button on it. When clicking device's button, notification characteristic updating and my app shows local notification. It's that simple.

I connect bluetooth device in foreground as below :

   var restoreOptions = [CBPeripheralManagerOptionRestoreIdentifierKey: "customIdentifier"]
   centralManager.connect(peripheral, options: restoreOptions)

Then setted notification characteristic value is true :

   peripheral.setNotifyValue(true, for: notificationCharacteristic)

When notification characteristic update, app shows local notification :

   func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
       showLocalNotification()
   }

When notification characteristic is change , didUpdateValueFor is triggered and local notification shows. There is no problem in foreground and background. But when application is terminated by user, bluetooth device is disconnected and didUpdateValueFor not triggered. I want to re-connect again bluetooth device when characteristic change even app is terminated by user. How can I do this ? I hope I can tell you my problem. Thank you.


回答1:


You need to enable and program you App to handle Core-Bluetooth Background Mode

this way you will be able to reconnect to the device if your App is killed by the OS to free some resources.

"Even if your app supports one or both of the Core Bluetooth background execution modes, it can’t run forever. At some point, the system may need to terminate your app to free up memory for the current foreground app—causing any active or pending connections to be lost, for instance. As of iOS 7, Core Bluetooth supports saving state information for central and peripheral manager objects and restoring that state at app launch time. You can use this feature to support long-term actions involving Bluetooth devices"

but you cannot reconnect if the user has terminated your App.



来源:https://stackoverflow.com/questions/47813624/re-connect-bluetooth-device-when-app-is-terminated-by-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!