管理连接

启动连接

找到附近的设备后,发现程序便可以发起连接。以下示例在发现设备后立即请求连接。

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

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

以上示例显示了两端是否自动接受连接,但您可能会希望以某种方式向用户显示这种选择,具体取决于您的用例。