จัดการการเชื่อมต่อ

เริ่มการเชื่อมต่อ

เมื่อพบอุปกรณ์ที่อยู่ใกล้เคียง ผู้ค้นหาจะเริ่มการเชื่อมต่อได้ ตัวอย่างต่อไปนี้ขอเชื่อมต่อกับอุปกรณ์ทันทีที่ ค้นพบ

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:) เมธอด delegate

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

เมื่อผู้ลงโฆษณายอมรับ ทั้ง 2 ฝ่ายจะได้รับการแจ้งเตือนและต้องยืนยัน การเชื่อมต่อผ่านconnectionManager(_:didReceive:from:verificationHandler:) วิธีการมอบสิทธิ์

เราขอแนะนำให้แอปยืนยันการเชื่อมต่อโดยใช้รหัสยืนยันที่ได้รับจากเมธอดผู้มอบสิทธิ์ ซึ่งเป็นวิธีที่ช่วยให้ ผู้ใช้ยืนยันได้ว่าตนกำลังเชื่อมต่อกับอุปกรณ์ที่ต้องการ อุปกรณ์ทั้ง 2 เครื่องจะได้รับรหัสเดียวกัน ซึ่งเป็นสตริงแบบสุ่มสั้นๆ และคุณเป็นผู้กำหนดวิธี ยืนยัน โดยปกติแล้วขั้นตอนนี้จะเกี่ยวข้องกับการแสดงโทเค็นในอุปกรณ์ทั้ง 2 เครื่อง และ ขอให้ผู้ใช้เปรียบเทียบและยืนยันด้วยตนเอง ซึ่งคล้ายกับกล่องโต้ตอบการจับคู่บลูทูธ

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

การเชื่อมต่อจะเสร็จสมบูรณ์เมื่อทั้ง 2 ฝ่ายยอมรับ หากฝ่ายใดฝ่ายหนึ่งหรือทั้ง 2 ฝ่ายปฏิเสธ ระบบจะทิ้งการเชื่อมต่อ

ตัวอย่างข้างต้นแสดงการเชื่อมต่อที่ทั้ง 2 ฝ่ายยอมรับโดยอัตโนมัติ แต่คุณอาจต้องการแสดงตัวเลือกนี้ต่อผู้ใช้ในบางวิธี ทั้งนี้ขึ้นอยู่กับกรณีการใช้งานของคุณ