How can I reconnect to device after disconnecting in Core Bluetooth

前端 未结 4 1904
庸人自扰
庸人自扰 2021-02-03 13:40

In Core Bluetooth, after connecting to a device, I turn off the device and the device is disconnected. But when I turn on the device again, there is no didDiscoverPeripher

4条回答
  •  梦毁少年i
    2021-02-03 14:25

    @Andras gave me the right path, but his answer is not complete anymore since iOS7.

    The best way to reconnect to a previous device is to use the retrievePeripherals(withIdentifiers:) method.

    This method does not call a delegate, but directly returns you a list of Peripherals, corresponding to the list of UUID passed in parameters.

    if let peripheral = self.centralManager.retrievePeripherals(withIdentifiers: [uuid]).first {
        self.peripheral = peripheral // <-- super important
        self.centralManager.connect(peripheral, options: nil)
    }
    

    Please check the "super important" line of the above code: The method connect(_:option:) does not retain the peripheral, and if you don't do it yourself, the connection will always fail without any callback since the peripheral objet will be destroyed.

提交回复
热议问题