编写使用CoreBluetooth框架的命令行应用程序

时间:2019-02-09 22:55:21

标签: swift

我正在尝试编写一个使用CoreBluetooth框架的命令行应用程序。

我已经见过CoreBluetooth on Mac Command line application,但是当我尝试遵循公认的建议时,我的程序与使用Cocoa制作的程序不同。

命令行应用程序的代码:

import Foundation
import CoreBluetooth

class MyBluetoothClient : NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
    var manager: CBCentralManager!

    override init() {
        super.init()
        manager = CBCentralManager(delegate: self, queue: nil)
        print("Launched!")
    }

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        central.scanForPeripherals(withServices: nil)
        print("Started scan!")
    }

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

_ = MyBluetoothClient()

let runLoop = RunLoop.current
while runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: NSDate.distantFuture) {}

该代码记录的唯一内容是:

Launched

以下可可应用程序开始扫描并检测到多个外围设备。

import Cocoa
import CoreBluetooth

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, CBCentralManagerDelegate, CBPeripheralDelegate {

    @IBOutlet weak var window: NSWindow!
    var manager: CBCentralManager!

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        central.scanForPeripherals(withServices: nil)
        print("Started scan!")
    }

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

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        manager = CBCentralManager(delegate: self, queue: nil)
        print("Launched!")
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
}

谢谢!

0 个答案:

没有答案