首页 > 解决方案 > 核心蓝牙发现未发现某些设备

问题描述

我有 3 台设备,1 部 iPhone,1 部 iPad,1 部 macbook,并使用核心蓝牙来发现其他设备。

iPad(外围设备)

iPhone(中央)

macbook(中央)

当 iPad/外围设备在做广告而其他设备处于中央模式时,我只能在 macbook 上发现它。iPhone 永远不会看到广告数据。如果我转换角色,同样的事情会再次发生。iOS 设备永远不会互相看到,只有 macbook 可以看到它们。我快疯了,不知道还能做什么。有任何想法吗?

BluetoothCentral.swift

import Foundation
import CoreBluetooth

class BluetoothCentral: NSObject, ObservableObject {
    var centralManager: CBCentralManager!
    override init(){
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: .main)
    }
    
}

extension BluetoothCentral: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
          case .unknown:
            print("central.state is .unknown")
          case .resetting:
            print("central.state is .resetting")
          case .unsupported:
            print("central.state is .unsupported")
          case .unauthorized:
            print("central.state is .unauthorized")
          case .poweredOff:
            print("central.state is .poweredOff")
          case .poweredOn:
            print("central.state is .poweredOn")
            centralManager.scanForPeripherals(withServices: nil)

        @unknown default:
            print("Unknown")
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print(peripheral)
        print("---------> \(peripheral.name)")
    }
}

蓝牙外设.swift

import Foundation
import CoreBluetooth

let SERVICE_NAME = "card-iphone"

class BluetoothPeripheral: NSObject, ObservableObject {
    var uuid:String = ""
    var peripheralManager: CBPeripheralManager?
    
    required override init() {
          super.init()
       }

    func start(uuid: String){
        self.uuid = uuid
        peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    }
}

extension BluetoothPeripheral: CBPeripheralManagerDelegate {
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if peripheral.state == .poweredOn {
            if peripheral.isAdvertising {
                peripheral.stopAdvertising()
            }
            let advertisingData: [String : Any] = [
                CBAdvertisementDataLocalNameKey: SERVICE_NAME
            ]
        
            self.peripheralManager?.startAdvertising(advertisingData)
        } else {
            print("handle other states")
        }
    }
}

在此处输入图像描述

标签: iosswiftcore-bluetooth

解决方案


推荐阅读