为什么我的苹果机不能在这个核心蓝牙应用程序中发现设备?

问题描述:

我一直在研究Core蓝牙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") 
} 
} 

它打印出“打开”,但没有“发现”。我尝试了多个蓝牙设备和扬声器。

+0

你还没有告诉CoreBluetooth发现任何设备。你需要调用'scanForPeripherals' – Paulw11

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