【问题标题】:List devices that are in range of Bluetooth device in Swift在 Swift 中列出蓝牙设备范围内的设备
【发布时间】:2014-08-10 20:22:30
【问题描述】:

我在 Xcode 6 操场上有以下代码:

import Cocoa
import IOBluetooth

class BlueDelegate : IOBluetoothDeviceInquiryDelegate {
    func deviceInquiryComplete(sender: IOBluetoothDeviceInquiry, error: IOReturn, aborted: Bool) {
        aborted
        var devices = sender.foundDevices()
        for device : AnyObject in devices {
            if let thingy = device as? IOBluetoothDevice {
                thingy.getAddress()
            }
        }
    }
}

var inquiry = IOBluetoothDeviceInquiry(delegate: BlueDelegate())
inquiry.start()

我刚刚开始在 OSX 下使用蓝牙,目前我想要的只是范围内的设备列表。

它似乎根本没有调用我的委托方法。

我是 OSX 开发和 Swift 的新手,所以要温柔。 :)

【问题讨论】:

    标签: macos bluetooth swift iobluetooth


    【解决方案1】:

    要告诉 Playground 您的代码在后台执行某些操作,您必须 import XCPlayground 并调用 XCPSetExecutionShouldContinueIndefinitely()
    这将使 IOBluetoothDeviceInquiry 在 Playground 中保持活动状态,并允许它在完成时调用委托方法。

    import Cocoa
    import IOBluetooth
    import XCPlayground
    
    class BlueDelegate : IOBluetoothDeviceInquiryDelegate {
        func deviceInquiryComplete(sender: IOBluetoothDeviceInquiry, error: IOReturn, aborted: Bool) {
            aborted
            println("called")
            var devices = sender.foundDevices()
            for device : AnyObject in devices {
                if let thingy = device as? IOBluetoothDevice {
                    thingy.getAddress()
                }
            }
        }
    }
    
    var delegate = BlueDelegate()
    var inquiry = IOBluetoothDeviceInquiry(delegate: delegate)
    inquiry.start()
    XCPSetExecutionShouldContinueIndefinitely()
    

    虽然上述方法有效,但我发现为需要异步代码、委托等概念的任务创建简单的传统测试项目更容易......

    【讨论】:

    • 您将如何使用“传统测试项目”来做到这一点?
    • 只需创建一个新的 Xcode 项目(而不是使用 Playground)。虽然使用 XCPSetExecutionShouldContinueIndefinitely 有效,但在测试项目发展时,编译的可执行文件(具有运行循环和附加调试器的能力)更容易处理。
    • 您可以在此处找到更新的 Swift 4.0 答案 (stackoverflow.com/questions/40636726/…)
    猜你喜欢
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多