在 Swift 中列出蓝牙设备范围内的设备 [英] List devices that are in range of Bluetooth device in Swift

查看:17
本文介绍了在 Swift 中列出蓝牙设备范围内的设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Xcode 6 Playground 中有以下代码:

I have the following code in a Xcode 6 playground:

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 下的蓝牙,目前我想要的是范围内的设备列表.

I'm just getting started with Bluetooth under OSX, and all I currently would like is a list of devices in range.

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

It doesn't seem to be calling my delegate method at all.

我是 OSX 开发和 Swift 的新手,所以请保持温和.:)

I'm new to OSX development and Swift, so be gentle. :)

推荐答案

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

To tell a Playground that your code does something in the background, you have to import XCPlayground and call XCPSetExecutionShouldContinueIndefinitely().
This will keep the IOBluetoothDeviceInquiry alive in the Playground and allow it to call the delegate method when finished.

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()

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

While the above approach works, I find it easier to create simple, traditional test projects for tasks that need concepts like async-code, delegation, ...

这篇关于在 Swift 中列出蓝牙设备范围内的设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆