我正在寻找一种方法,以编程方式列出我的设备找到的任何附近的蓝牙设备(可发现的)。在Swift 3.0中,我没有找到任何有关执行此调用的信息或教程。本Q-A员额讨论使用SWIFT1.0和构建Xcode 6,而不是最新版本8来查找这些设备。
我尽力让我的代码从1.0变成3.0语法,但是在运行下面的代码时,游乐场中没有返回任何内容:
import Cocoa
import IOBluetooth
import PlaygroundSupport
class BlueDelegate : IOBluetoothDeviceInquiryDelegate {
func deviceInquiryComplete(_ sender: IOBluetoothDeviceInquiry, error: IOReturn, aborted: Bool) {
aborted
print("called")
let devices = sender.foundDevices()
for device : Any? in devices! {
if let thingy = device as? IOBluetoothDevice {
thingy.getAddress()
}
}
}
}
var delegate = BlueDelegate()
var inquiry = IOBluetoothDeviceInquiry(delegate: delegate)
inquiry?.start()
PlaygroundPage.current.needsIndefiniteExecution = true
发布于 2017-01-30 17:05:56
正确使用IOBluetooth
以下代码在Xcode版本8.2.1 (8C1002)、Swift 3.0中运行得非常完美。有些行是不需要的,例如deviceInquiryStarted
的整个方法。
更新:这些用法在Xcode 9.2 (9B55)和Swift 4.中仍然有效。
游乐场
import Cocoa
import IOBluetooth
import PlaygroundSupport
class 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 = true
ibdi?.start()
PlaygroundPage.current.needsIndefiniteExecution = true
项目-应用程序使用
import Cocoa
import IOBluetooth
import ...
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 = true
ibdi?.start() //recommended under after an action-button press.
解释
由于调查仍在进行中,我最初面临的问题是设法获取信息。
当我访问它时,在许多不同的情况下,我的操场会挂起,我将被迫退出活动监视器中的Xcode.app和com.apple.CoreSimulator.CoreSimulatorService
。我让自己相信,这只是一个游乐场的错误,只是知道我的应用程序将崩溃,一旦调查结束。
正如苹果的API参考所说:
重要注意事项:不要在来自委托方法的设备上或在使用此对象时执行远程名称请求。如果希望在设备上执行自己的远程名称请求,请在停止此对象后执行它们。如果不注意此警告,则可能会导致进程死锁。
这完全解释了我的问题。而不是直接从IOBluetoothDevice
方法中请求sender.foundDevices()
信息(我认为该方法可能没有更新.?)我只是使用函数中内置的参数来说明它确实是一个IOBluetoothDevice
对象,并且只是要求打印这些信息。
最后注
我希望我创建的这个Q/A在Swift中使用IOBluetooth
时能帮助其他需要帮助的人。由于缺乏任何教程和大量过时的客观C代码,因此发现这些信息非常具有挑战性。我要感谢@RobNapier支持我在一开始就试图找到这个谜语的答案。我还要感谢NotMyName在苹果开发者论坛上对我的帖子的回复。
我将更早地探索在iOS设备中使用这种技术的方法!
https://stackoverflow.com/questions/40636726
复制相似问题