ios - 应用终止时CoreBluetooth建立外围连接
问题描述
我有一个 iOS 应用程序,它通过 CoreBluetoothcentral
连接到外部。peripheral
连接到 后peripheral
,我对其进行读取和写入数据,然后断开连接。断开连接后,我尝试再次建立连接,以便下次peripheral
进入advertise
模式时,应用程序将连接到它,如下所示:
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
central.connect(peripheral, options: nil)
// More actions here...
}
当应用程序位于 / 时,它工作得很好,但当应用程序位于foreground
/background
时terminated
,它根本不起作用。
我已经定义了CBCentralManager
这样的CBCentralManagerOptionRestoreIdentifierKey
:
self.central = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: Application.bluetoothRestoreIdentifier])
我还实现了willRestoreState
中央委托方法:
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any])
我究竟做错了什么?
非常感谢!
解决方案
试试下面的代码
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
let connectedperipherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral]
if let peripheral = connectedperipherals?.first {
central.connect(peripheral, options: nil)
}
}
推荐阅读
- python - cv2 在 Python 中不会出错,因此不能与 except 块一起使用
- html - 如何在 Folium GeoJson 弹出窗口中包装溢出文本?
- javascript - 音频开始下载而不是播放(Vue)
- typescript - 如何“重新启用”来自其他选项卡的认知令牌?
- html - Reactjs 动画滞后
- javascript - 将 D3 树从垂直旋转到水平
- xamarin.forms - 尝试发布新版本的应用程序 - “无效的工具链。您的应用程序已构建...”
- mips - MIPS 中的内存地址越界错误,但在不同的函数中工作
- eclipse - eclipse sts gradle 多模块项目问题
- python - 作业中的冒号 (:) 是什么意思?