简体   繁体   English

Mac 上的 CoreBluetooth 命令行应用程序

[英]CoreBluetooth on Mac Command line application

I'm trying to build a Command Line app that uses CoreBluetooth.我正在尝试构建一个使用 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.我已将我的CoreBluetooth代码(一个实现 CBCentralManagerDelegate 协议的类 - 我们称这个类myBLEManager )从命令行应用程序项目移动到另一个 Mac OS GUI 应用程序。

I ran some tests in ViewDidLoad() -- supersample, I just init a myBLEManager that creates an instance of CBCentralManager on initialization, then calls scanForPeripherals .我在ViewDidLoad()中运行了一些测试——超级样本,我只是初始化了一个myBLEManager ,它在初始化时创建了一个CBCentralManager的实例,然后调用scanForPeripherals

This is what I do in both the CLI and GUI projects.这就是我在 CLI 和 GUI 项目中所做的。 Difference is centralManagerDidUpdateState never gets called in the CLI project.区别是centralManagerDidUpdateState永远不会在 CLI 项目中被调用。 but it does in the GUI Mac app.但它确实在 GUI Mac 应用程序中。

Callbacks in most Apple frameworks are delivered through your application's main run loop.大多数 Apple 框架中的回调是通过应用程序的主运行循环传递的。 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:在 Swift 5+ 中,这是 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) {
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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