接続を管理

接続を開始する

付近のデバイスが検出されると、検出機能が接続を開始します。次の例では、検出後すぐにデバイスとの接続をリクエストします。

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

双方が承諾した場合にのみ、接続が確立されます。一方または両方が拒否されると、接続は破棄されます。

上記の例では、両側で接続が自動的に受け入れられますが、ユースケースによっては、この選択肢をなんらかの方法でユーザーに提示することもできます。