8

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. :)

James Zaghini
  • 3,895
  • 4
  • 45
  • 61
Xenph Yan
  • 83,019
  • 16
  • 48
  • 55

1 Answers1

7

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

Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
  • How exactly would you do this using a "traditional test projects"? – cocoseis Oct 24 '15 at 13:17
  • Just create a new Xcode project (instead of using a Playground). While using XCPSetExecutionShouldContinueIndefinitely works, a compiled executable (with a runloop and the ability to attach a debugger) is easier to handle when the test project evolves. – Thomas Zoechling Oct 24 '15 at 16:27
  • You can find an updated Swift 4.0 answer here (https://stackoverflow.com/questions/40636726/nearby-bluetooth-devices-using-swift-3-0?noredirect=1&lq=1) – Dylan Oct 18 '17 at 13:09