0

我正在尝试开发基于蓝牙的应用程序,该应用程序将为用户提供通过蓝牙配对共享数据的功能。我在配对设备时遇到问题。

这是我的场景 用户将登录应用程序并提示启用蓝牙服务。这是相同的代码:-

//MARK: - DECLARATIONS
var cbCentralManager : CBCentralManager?
var peripheral : CBPeripheral?
var peripherals: [CBPeripheral] = []

//MARK: - VIEW_METHODS
override func viewDidLoad() {
    super.viewDidLoad()
    self.setUpView()
}

func setUpView() {
    cbCentralManager = CBCentralManager(delegate: self, queue: nil)
    
}

//MARK: - EXTENSION
extension ViewController : CBCentralManagerDelegate {

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        print("Bluetooth is enabled..")
        central.scanForPeripherals(withServices: nil, options: nil)
    } else {
        print("Bluetooth is not enabled..")
    }
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    
    guard peripheral.name != nil else {return}
        
        print("Sensor Found!")
        //stopScan
        cbCentralManager?.stopScan()
        
        //connect
        cbCentralManager?.connect(peripheral, options: nil)
        self.peripheral = peripheral
}
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    //discover all service
    
    peripheral.discoverServices(nil)
    peripheral.delegate = self
    
}

在下一步中,单击按钮,将扫描附近的 BLE 设备。

func startScan() {
    let options: [String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey:
                                    NSNumber(value: false)]
    peripherals = []
    print("Now Scanning...")
    self.timer.invalidate()
    centralManager?.scanForPeripherals(withServices: nil, options: options)
    Timer.scheduledTimer(timeInterval: 17, target: self, selector: #selector(self.cancelScan), userInfo: nil, repeats: false)
}

用户从扫描的 BLE 设备列表中选择要配对的设备后,将执行以下代码以建立设备之间的连接。

func connectToDevice(device:CBPeripheral) {
    centralManager = CBCentralManager(delegate: self, queue: .main)
    self.blePeripheral = device
    self.blePeripheral?.delegate = self
    centralManager?.connect(self.blePeripheral!, options: nil)
}

委托方法已扩展

extension HomeVC : CBPeripheralDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
    if peripheral.state == .poweredOn {
        return
    }
    print("Peripheral manager is running")
}
//Check when someone subscribe to our characteristic, start sending the data
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
    print("Device subscribe to characteristic")
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    
    print("*******************************************************")

    if ((error) != nil) {
        print("Error discovering services: \(error!.localizedDescription)")
        return
    }

    guard let services = peripheral.services else {
        return
    }
    //We need to discover the all characteristic
    for service in services {

        peripheral.discoverCharacteristics(nil, for: service)
        // bleService = service
    }
   
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
  
            if ((error) != nil) {
                print("Error discovering services: \(error!.localizedDescription)")
                return
            }
    
            guard let services = peripheral.services else {
                return
            }
            //We need to discover the all characteristic
            for service in services {
    
                peripheral.discoverCharacteristics(nil, for: service)
                // bleService = service
            }
            print("Discovered Services: \(services)")
    
        }

func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
    if let error = error {
        print("\(error)")
        let errorStr = "\(error)"
        let alert = UIAlertController(title: "Alert", message: errorStr, preferredStyle:     UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
        return
    }
}
}

我被卡住了,因为我没有收到配对设备的警报。任何人都可以指导我吗?提前致谢。

4

0 回答 0