为什么我的Mac发现设备在这个核心蓝牙应用程序?

时间:2017-08-25 20:16:47

标签: macos bluetooth core-bluetooth

我一直在使用Core Bluetooth Mac应用程序,而且我在Mac上遇到了与发现部分有关的问题。尽管我的mac的蓝牙设置中出现了相同的设备,但此代码未能发现任何设备。显然它是一个代码问题,但我似乎无法弄明白。代码:

import Cocoa
import CoreBluetooth

class ViewController: NSViewController, CBCentralManagerDelegate {
var centralManager: CBCentralManager!
override func viewDidLoad() {
    super.viewDidLoad()
    centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)

    // Do any additional setup after loading the view.
}

override var representedObject: Any? {
    didSet {
    // Update the view, if already loaded.
    }
}

func setupBT() {

}

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    var statusMessage = ""
    switch central.state {
    case .poweredOn:
        statusMessage = "Bluetooth Status: Turned On"

    case .poweredOff:
        statusMessage = "Bluetooth Status: Turned Off"

    case .resetting:
        statusMessage = "Bluetooth Status: Resetting"

    case .unauthorized:
        statusMessage = "Bluetooth Status: Not Authorized"

    case .unsupported:
        statusMessage = "Bluetooth Status: Not Supported"

    default:
        statusMessage = "Bluetooth Status: Unknown"
    }

    print(statusMessage)
}

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

正在打印"打开"但没有"发现"。我试过多个蓝牙设备和扬声器。

1 个答案:

答案 0 :(得分:0)

您需要致电scanForPeripherals(withServices:options:)以发现外围设备。请注意,您必须等待CBCentralManager处于poweredOn州。否则,什么都不会发生,您可能会在控制台中看到一些警告和错误日志。