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.
説明
私が最初に直面した問題は、調査がまだ進行中であったため、情報にアクセスしようとすることでした。
com.apple.CoreSimulator.CoreSimulatorService
アクセスすると、さまざまな状況でプレイグラウンドがハングし、Xcode.app とアクティビティ モニターの両方を強制終了する必要がありました。これは単なる Playground のバグだと思い込んでいたのですが、調査が完了するとアプリケーションがクラッシュすることがわかったのです。
Apple のAPI リファレンスには次のように記載されています。
重要な注意: デリゲート メソッドから、またはこのオブジェクトの使用中に、デバイスでリモート名要求を実行しないでください。デバイスで独自のリモート名要求を行いたい場合は、このオブジェクトを停止してから実行してください。この警告に注意しないと、プロセスがデッドロックする可能性があります。
これは私の問題を完全に説明しました。IOBluetoothDevice
メソッドから情報を直接要求するのではなくsender.foundDevices()
(更新されていない可能性があると思います..?)、関数に組み込まれているパラメーターを使用して、それが実際にIOBluetoothDevice
オブジェクトであることを伝え、単にその情報がオブジェクトであることを要求しました。印刷されます。
ファイナルノート
私が作成したこの Q/A がIOBluetooth
、Swift で使用するときに困っている人に役立つことを願っています。チュートリアルがなく、大量の旧式の Objective-C コードがあるため、この情報を見つけるのは非常に困難でした。最初にこのなぞなぞの答えを見つけようとしてくれた @RobNapier に感謝します。また、Apple Developer Forums の私の投稿に返信してくれた NotMyName にも感謝します。
遅かれ早かれ、iOS デバイスでこれを使用する方法を検討する予定です。