swift - Mac 命令行应用程序上的 CoreBluetooth

标签 swift cocoa core-bluetooth

我正在尝试构建一个使用 CoreBluetooth 的命令行应用程序。问题是,它不适用于命令行应用程序。

我已经将我的 CoreBluetooth 代码(一个实现 CBCentralManagerDelegate 协议(protocol)的类 - 我们称这个类为 myBLEManager)从命令行应用程序项目移动到另一个 Mac 操作系统GUI 应用程序。

我在 ViewDidLoad() 中运行了一些测试—— super 样本,我只是初始化了一个 myBLEManager,它在初始化时创建了一个 CBCentralManager 的实例,然后调用 scanForPeripherals

这是我在 CLI 和 GUI 项目中所做的。区别在于 centralManagerDidUpdateState 永远不会在 CLI 项目中被调用。但它在 GUI Mac 应用程序中确实如此。

最佳答案

大多数 Apple 框架中的回调都是通过应用程序的主运行循环传递的。如果您的命令行工具没有运行循环,则它无法接收以这种方式发送的回调。

如果没有 runloop,框架调用回调的唯一方法是在另一个线程上运行它,这可能会导致应用程序出现意想不到的奇怪行为。

添加就足够了:

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

}

关于swift - Mac 命令行应用程序上的 CoreBluetooth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42634584/

相关文章:

cocoa - 自动创建冲突的 NSFileVersions

iphone - 导航到已加载的主 ViewController 而无需再次加载

cocoa - DDHotKeyCenter 'implicit conversion' 警告

ios - iPhone 蓝牙 : specification of the native camera app control

Swift ENUM 如何将 "rawValue"转换回枚举大小写?

swift - 我想将 RawRepresentable 的 rawValue 作为 Any 返回,但我只将它作为 Any 接收

ios - 在 iOS 蓝牙外设上查找 TxPower

iphone - 使用 Corebluetooth 框架检测耳机

ios - 识别 subview

swift - 订阅返回的发布者后如何触发流程?