接続を開始する
付近のデバイスが検出されると、検出側が接続を開始できます。次の例では、デバイスが検出されるとすぐに接続をリクエストします。
Swift
extension Example: DiscovererDelegate {
func discoverer(
_ discoverer: Discoverer, didFind endpointID: EndpointID, with context: Data) {
// An endpoint was found. We request a connection to it. The endpoint info can be used
// to provide arbitrary information to the discovering device (e.g. device name or type).
discoverer.requestConnection(to: endpointID, using: "My Device".data(using: .utf8)!)
}
func discoverer(_ discoverer: Discoverer, didLose endpointID: EndpointID) {
// A previously discovered endpoint has gone away.
}
}
ユースケースによっては、検出されたデバイスのリストをユーザーに表示して、接続するデバイスを選択できるようにすることもできます。
接続を承諾または拒否する
検出側が広告主に接続をリクエストすると、広告主は advertiser(_:didReceiveConnectionRequestFrom:with:connectionRequestHandler:) デリゲート メソッドを介して接続リクエストの通知を受け取ります。
Swift
extension Example: AdvertiserDelegate {
func advertiser(
_ advertiser: Advertiser, didReceiveConnectionRequestFrom endpointID: EndpointID,
with context: Data, connectionRequestHandler: @escaping (Bool) -> Void) {
// Call with `true` to accept or `false` to reject the incoming connection request.
connectionRequestHandler(true)
}
}
広告主が承諾すると、両側に通知が届き、connectionManager(_:didReceive:from:verificationHandler:) デリゲート メソッドを介して接続を確認する必要があります。
アプリでは、デリゲート メソッドから提供された確認コードを使用して接続を確認することをおすすめします。これにより、ユーザーは意図したデバイスに接続していることを確認できます。両方のデバイスに同じコード(短いランダムな文字列)が表示されます。確認方法は任意です。通常は、両方のデバイスにトークンを表示し、Bluetooth ペアリング ダイアログと同様に、ユーザーに手動で比較して確認してもらいます。
Swift
extension Example: ConnectionManagerDelegate {
func connectionManager(
_ connectionManager: ConnectionManager, didReceive verificationCode: String,
from endpointID: EndpointID, verificationHandler: @escaping (Bool) -> Void) {
// Optionally show the user the verification code. Your app should call this handler
// with a value of `true` if the nearby endpoint should be trusted, or `false`
// otherwise.
verificationHandler(true)
}
}
接続が完全に確立されるのは、両側が承諾した場合のみです。どちらか一方または両方が拒否した場合、接続は破棄されます。
上記の例では、両側で接続が自動的に承諾されていますが、ユースケースによっては、この選択肢をユーザーに提示することもできます。