管理连接

发起连接

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

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

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

上述示例显示的是双方自动接受连接,但根据您的使用情形,您可能希望以某种方式向用户显示此选择。