List devices that are in range of Bluetooth device in Swift

♀尐吖头ヾ 提交于 2019-12-17 19:28:16

问题


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

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.

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


回答1:


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, ...



来源:https://stackoverflow.com/questions/24321126/list-devices-that-are-in-range-of-bluetooth-device-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!