正确使用IOBluetooth
下面的代码在Xpre版本8.2.1(8C1002),Swift3.0中可以正常工作。不需要几行,例如的整个方法
deviceInquiryStarted。
更新:从Xpre 9.2(9B55)和Swift 4开始,这些用法仍然有效。
操场
import Cocoaimport IOBluetoothimport PlaygroundSupportclass BlueDelegate : IOBluetoothDeviceInquiryDelegate { func deviceInquiryStarted(_ sender: IOBluetoothDeviceInquiry) { print("Inquiry Started...")//optional, but can notify you when the inquiry has started. } func deviceInquiryDeviceFound(_ sender: IOBluetoothDeviceInquiry, device: IOBluetoothDevice) { print("(device.addressString!)") } func deviceInquiryComplete(_ sender: IOBluetoothDeviceInquiry!, error: IOReturn, aborted: Bool) {//optional, but can notify you once the inquiry is completed. }}var delegate = BlueDelegate()var ibdi = IOBluetoothDeviceInquiry(delegate: delegate)ibdi?.updateNewDeviceNames = trueibdi?.start()PlaygroundPage.current.needsIndefiniteExecution = true项目应用用法
import Cocoaimport IOBluetoothimport ...class BlueDelegate : IOBluetoothDeviceInquiryDelegate { func deviceInquiryStarted(_ sender: IOBluetoothDeviceInquiry) { print("Inquiry Started...")} func deviceInquiryDeviceFound(_ sender: IOBluetoothDeviceInquiry, device: IOBluetoothDevice) { print("(device.addressString!)") }}//other classes here://reference the following outside of any class:var delegate = BlueDelegate()var ibdi = IOBluetoothDeviceInquiry(delegate: delegate)//refer to these specifically inside of any class:ibdi?.updateNewDeviceNames = trueibdi?.start() //recommended under after an action-button press.说明
由于查询仍在进行中,我最初遇到的问题是尝试访问信息。
当我访问它时,在许多不同的情况下,我的游乐场都将挂起,并且我将不得不强制退出Xpre.app和
com.apple.CoreSimulator.CoreSimulatorService活动监视器。我让自己相信这只是一个Playground错误,只是得知查询完成后我的应用程序将崩溃。
正如AppleAPI参考所指出的那样:
重要说明:请勿使用委托方法在设备上或使用此对象时在设备上执行远程名称请求。如果希望在设备上进行自己的远程名称请求,请在停止该对象后再进行。如果您不注意此警告,则可能导致进程死锁。
这完全解释了我的问题。与其直接
IOBluetoothDevice从
sender.foundDevices()方法中询问信息(我认为可能没有更新..?),我只是使用函数中内置的参数来提及它确实是一个
IOBluetoothDevice对象,而只是索要该信息是打印。
最后说明
我希望我创建的这个Q / A可以
IOBluetooth在Swift中使用时帮助需要帮助的其他人。缺少任何教程以及大量的过时的Objective-
C代码使查找此信息非常具有挑战性。我要感谢@RobNapier对试图找到这个问题的答案支撑 谜 的开始。我还要感谢NotMyName对我在Apple
Developer Forums上的帖子的答复。
我将更早探索在iOS设备中使用此功能的方法!



