繁体   English   中英

无法让 Core Bluetooth 在 Swift iOS 游乐场中工作

[英]Can't get Core Bluetooth to work in Swift iOS playground

我是 swift 的新手。 我无法在操场上获得对 centralManagerDidUpdateState:: 的回调(即:我认为初始化会回调到 centralManagerDidUpdateState):

import CoreBluetooth
class BTDiscovery:NSObject,
CBCentralManagerDelegate {

    func centralManagerDidUpdateState(central: CBCentralManager!) {
        println("here")
    }
}

var bt = BTDiscovery()

iOS Swift Playground 中是否支持 Core Bluetooth? 我为 OSX playground 和 IOBluetooth 尝试了这个。 这也不起作用。 我究竟做错了什么?

谢谢你。

我认为您遇到的是游乐场本质上是同步的,而蓝牙发现是异步的。 为了让它工作,你需要向你的 Playground 添​​加一些东西以允许异步操作:

import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

另请注意,由于 iOS 游乐场是在模拟器上运行的,我根本不希望 CB 在那里工作。

您还有更基本的问题,因为您没有做任何事情来实际触发发现。 您需要创建CBCentralManager的实例并使用它来驱动发现过程:

import Cocoa
import XCPlayground
import CoreBluetooth

class BTDiscovery:NSObject, CBCentralManagerDelegate {

    func centralManagerDidUpdateState(central: CBCentralManager!) {
        println("here")
    }

}

var bt = BTDiscovery()
var central = CBCentralManager(delegate: bt, queue: dispatch_get_main_queue())

XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

您只能在实际的 iOS 设备上使用 Core Bluetooth; 它在模拟器中不受支持,并且通过扩展,它在 Playground 中不受支持,因为它也在您的 Mac 上而不是在 iOS 设备上执行。

XCPSetExecutionShouldContinueIndefinitelyPlaygroundPage.current.needsIndefiniteExecution都可以工作。

请记住 CoreBluetooth 仅适用于设备。 这意味着目前它不能在 Playground 上工作。

可以在 Swift Playground 中使用蓝牙。 请注意,您必须使用PlaygroundBluetooth 您可以在 文档框架 PlaygroundBluetooth 中找到有关它的更多信息

这是您可以使用中央扫描的方式。

let managerDelegate: PlaygroundBluetoothCentralManagerDelegate = <# manager delegate instance #>

let manager = PlaygroundBluetoothCentralManager(services: nil)
manager.delegate = managerDelegate

请注意PlaygroundBluetooth只是CoreBluetooth一个子集,因此您无法完成CoreBluetooth通常可以做到的所有事情,但我认为它仍然可以让简单的事情变得有趣。

暂无
暂无

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

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