연결 관리

연결 시작

근처 기기가 발견되면 검색자가 연결을 시작할 수 있습니다. 다음 예에서는 기기가 검색되는 즉시 기기와의 연결을 요청합니다.

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

양쪽 모두 수락해야 연결이 완전히 설정됩니다. 한쪽 또는 양쪽 모두 거부하면 연결이 삭제됩니다.

위의 예시에서는 양쪽에서 연결을 자동으로 수락하지만 사용 사례에 따라 이 선택사항을 사용자에게 어떤 방식으로든 표시할 수 있습니다.