接続を管理する

接続を開始する

付近のデバイスが見つかると、検出側は接続を開始できます。次の例では、デバイスが検出されるとすぐにデバイスとの接続をリクエストしています。

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)
  }
}

接続が完全に確立されるのは、両側が承認した場合のみです。一方または両方が拒否した場合、接続は破棄されます。

上記の例では、接続が双方で自動的に受け入れられていますが、ユースケースによっては、この選択をなんらかの方法でユーザーに提示することが望ましい場合もあります。