iOS swift5 gets the bluetooth devices connected to the system or other apps

chatGPT answers

To obtain the connected Bluetooth devices of the system or other apps, you can use the CBCentralManager class provided by the CoreBluetooth framework. Here is sample code using Swift 5:

import CoreBluetooth

class BluetoothManager: NSObject, CBCentralManagerDelegate {
    
    

    var centralManager: CBCentralManager!
    
    override init() {
    
    
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
    
    
        if central.state == .poweredOn {
    
    
            // 扫描已连接的外设
            let connectedPeripherals = centralManager.retrieveConnectedPeripherals(withServices: [/* 服务UUID */])
            for peripheral in connectedPeripherals {
    
    
                print(peripheral.name)
                // 如果需要,你可以保存已连接的外设以供后续使用
            }
        }
    }
}

In the above example, when the CBCentralManager object is initialized, you must provide a proxy object to receive event notifications from the Bluetooth Central Manager. Then, you can implement the centralManagerDidUpdateState method, which is called when the state of the Bluetooth central manager is updated. In this method, you can use the retrieveConnectedPeripherals(withServices:) method to get the list of connected peripherals. It should be noted that you need to specify the UUID of the service to be scanned, so that you can get the connected peripherals of the corresponding service.

My instance

reference blog

ios Bluetooth scan specified device scanForPeripheralsWithServices (filter out other devices, leaving only your own device) - csdn
iOS Bluetooth development connection system or Bluetooth devices that have been connected and successfully paired with other APPs - CSDN

Guess you like

Origin blog.csdn.net/baidu_40537062/article/details/130698427