本文介绍了didDiscover外设未调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想使用CBCentralManager来查找我周围的蓝牙低功耗外围设备. centralManager正在启动,它可以正确启动并且正在扫描.但是didDiscover函数从不被调用.我阅读了有关此问题和类似问题的所有其他文章,并有99%的把握确定我的问题的起因不相同.不过,我找不到我做错了什么.

I want to use the CBCentralManager in order to find the bluetooth low energy peripherals around me. The centralManager is getting initiated, it starts correctly and it is scanning. But the didDiscover function is never called. I read all the other posts to this and similar problem and am 99% sure that my problem has not the same cause. Still, I cannot find what I did wrong.

import Foundation
import CoreBluetooth

@objc(SmallerBeaconServiceImpl)
class SmallerBeaconServiceImpl : NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {

    private let centralManager : CBCentralManager

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == CBManagerState.poweredOn && isRunning {
            startScanningForPeripherals()
        }
        print("updated state: \(central.state)")
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print(peripheral.name ?? "no name")
    }

    func startScanningForPeripherals() {
        if centralManager.state != CBManagerState.poweredOn {
            return
        }

        centralManager.scanForPeripherals(withServices: nil, options: nil)
        print("is scanning: \(centralManager.isScanning)")
    }


    private(set) var isRunning = false

    func startListening() {
        if isRunning {
            return
        }

        isRunning = true

        print("started.")
        startScanningForPeripherals()
    }

    func stopListening() {
        if !isRunning {
            return
        }
        isRunning = false

        centralManager.stopScan()
    }

    override init() {
        centralManager = CBCentralManager()
        super.init()

        print("initiated")
    }
}

推荐答案

optional func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber)CBCentralManagerDelegate方法.

您的类SmallerBeaconServiceImplCBCentralManagerDelegate兼容,但是您没有设置centralManager delegate(CBCentralManagerDelegate)属性.这就是为什么不调用centralManager(_central:didDiscover:advertisementData:rssi)的原因.

Your class SmallerBeaconServiceImpl is compliant with CBCentralManagerDelegate, but you didn't set your centralManager delegate (CBCentralManagerDelegate) property. That's why centralManager(_central:didDiscover:advertisementData:rssi) is not called.

此问题可以通过以下方式解决:

This can be fixed with:

centralManager = CBCentralManager(delegate: self, queue: nil)

这篇关于didDiscover外设未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 17:21