管理连接

发起连接

发现附近的设备后,发现者可以发起连接。以下示例会在发现设备后立即请求与其建立连接。

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:) 委托方法验证连接。

建议您的应用使用委托方法提供的验证码来验证连接。这样,用户就可以确认他们连接的是预期的设备。两台设备都会获得相同的代码,这是一个简短的随机字符串;您可以自行决定如何验证该代码。这通常涉及在两台设备上显示令牌,并要求用户手动比较和确认,类似于蓝牙配对对话框。

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

只有在双方都接受后,连接才会完全建立。如果其中一方或双方拒绝,则连接会被舍弃。

前面的示例展示了双方自动接受连接,但根据您的用例,您可能希望以某种方式向用户呈现此选择。