简体   繁体   中英

CoreBluetooth on Mac Command line application

I'm trying to build a Command Line app that uses CoreBluetooth. Problem is, it doesn't work on command line apps.

I've moved the my CoreBluetooth code (a class that implements the CBCentralManagerDelegate protocol - let's call this class myBLEManager ) from the Command Line app project to another Mac OS GUI App.

I ran some tests in ViewDidLoad() -- supersample, I just init a myBLEManager that creates an instance of CBCentralManager on initialization, then calls scanForPeripherals .

This is what I do in both the CLI and GUI projects. Difference is centralManagerDidUpdateState never gets called in the CLI project. but it does in the GUI Mac app.

Callbacks in most Apple frameworks are delivered through your application's main run loop. If your command-line tool does not have a run loop, it cannot receive callbacks that are sent this way.

Without a runloop, the only way for the framework to invoke your callback would be to run it on another thread, which could lead to weird behavior in an application that didn't expect that.

It's sufficient to add:

let runLoop = RunLoop.current
let distantFuture = Date.distantFuture
while running == true && runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: distantFuture) {

}

In Swift 5+ this is the syntax for a Runloop:

import Foundation

let runLoop = RunLoop.current
let distantFuture = Date.distantFuture
var shouldKeepRunning = true

while shouldKeepRunning == true && runLoop.run(mode: RunLoop.Mode.default, before: distantFuture) {
    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM