2017-08-25 48 views
0

我一直在研究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

回答

0

您需要致電scanForPeripherals(withServices:options:)才能發現外圍設備。請注意,您必須等待CBCentralManager處於poweredOn狀態。否則,什麼都不會發生,您可能會在控制檯中看到一些警告和錯誤日誌。

相關問題