Manage connections

Initiate a connection

When nearby devices are found, the discoverer can initiate connections. The following example requests a connection with a device as soon as it is discovered.

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

Depending on your use case, you may wish to instead display a list of discovered devices to the user, allowing them to choose which devices to connect to.

Accept or reject a connection

After the discoverer has requested a connection to an advertiser, the advertiser is notified of the connection request via the advertiser(_:didReceiveConnectionRequestFrom:with:connectionRequestHandler:) delegate method.

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

Once the advertiser accepts, both side are notified and must verify the connection via the connectionManager(_:didReceive:from:verificationHandler:) delegate method.

It is recommended that your app verifies the connection by using the verification code provided by the delegate method. This provides a way to let users confirm that they are connecting to the intended device. Both devices are given the same code, which is a short random string; it's up to you to decide how to verify it. Typically this involves showing the token on both devices and asking the users to manually compare and confirm, similar to a bluetooth pairing dialog.

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

The connection is fully established only when both sides have accepted. If one or both reject, the connection is discarded.

The above examples shows the connection being automatically accepted by both sides, but depending on your use case you may wish to present this choice to the user in some way.