为什么移动到新场景时蓝牙会断开?

Why does bluetooth disconnect when I move to a new scene?

我正在开发一个 iOS 应用程序,我正在尝试连接到 nrf52840 开发工具包。当我在一个场景中连接到它时它连接没问题,调试菜单告诉我它连接,当我移动到另一个场景时它断开连接。

我已经尝试将连接移动到代码的不同区域,但没有任何改变。


import UIKit
import CoreBluetooth


class ViewController: UIViewController, CBCentralManagerDelegate {


    private var centralManager : CBCentralManager!

    private var blePeripheral : CBPeripheral!

    private var uniqueID : Any!



   // manager = CBCentralManager(delegate: self, queue: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
        // Do any additional setup after loading the view, typically from a nib.
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10.0) {
            print("Connecting to peripheral \(self.peripheral)")
        }
        if(centralManager != nil){
            if isConnectedtoAnything(){
                print("not scanning")
                print(centralManager.debugDescription)
            }else{
                print("scanning")
            }
        }
    }
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            print("Bluetooth is On")
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        } else {
            print("Bluetooth is not activate")
        }
    }

    @IBAction func StartSearch() {
        print("starting Search")
        centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
    }

    @IBAction func StopConn() {
        if centralManager.isScanning {
            print("Do Nothing")
        }else{
            print("cancelling Connection")
            centralManager.cancelPeripheralConnection(blePeripheral)
        }
    }

    public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("\nName    : \(peripheral.name ?? "(No name)")")
        if peripheral.name == "Device_Name"{
                print("Found the Device")

            blePeripheral=peripheral
            central.connect(blePeripheral, options: nil)
            central.stopScan()
            if !central.isScanning{
                print("===============================")
                print("Connected Successfuly")
            }
        }

        print("RSSI     : \(RSSI)")
        for ad in advertisementData{
            print("AD Data:     \(ad)")


        }
    }
    func isConnectedtoAnything() ->Bool{
        if centralManager.isScanning {
            print("It is scanning ")
            return false
        }
        else {
            return true
        }
    }



    func peripheral(peripheral: CBPeripheral,
                    didUpdateValueForCharacteristic characteristic: CBCharacteristic,
                    error: NSError?)
    {
        if let error = error {
            print("Failed… error: \(error)")
            return
        }
        print("characteristic uuid: \(characteristic.uuid), value: \(characteristic.value)")
    }

    func centralManager(_ central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral,
                        advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!)
    {
        print("Peripheral : \(peripheral)")

    }

我只想让应用保持与开发工具包的连接

我不确定这是否是问题所在。但是在视图控制器中声明连接句柄及其委托并不是一个好习惯。当您移动到新的视图控制器时,由于从该实例调用了 viewDidDisappear(),可能不会调用委托。

而是创建一个单例 Class,它仅在 class 中维护所有必需的连接对象和委托。然后从视图控制器中获取一个实例来建立连接。如果你移动到一个新的视图控制器,再次从单例中获取实例 class 以从新的视图控制器发送或接收数据。

我以相同的方式维护跨多个视图控制器的连接。