ניהול החיבורים

יצירת חיבור

כשמאתרים מכשירים בקרבת מקום, ה-Discover יכול ליזום חיבורים. בדוגמה הבאה מוצגת בקשה לחיבור עם המכשיר כשהוא מתגלה.

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:).

מומלץ שהאפליקציה שלכם תאמת את החיבור באמצעות קוד האימות שסופק על ידי שיטת ההאצלה. כך המשתמשים יכולים לאשר שהם מתחברים למכשיר הרצוי. שני המכשירים מקבלים את אותו הקוד, מחרוזת אקראית קצרה, ואתם מחליטים איך לאמת אותו. בדרך כלל צריך להציג את האסימון בשני המכשירים ולבקש מהמשתמשים להשוות ולאשר באופן ידני, כמו בתיבת הדו-שיח להתאמה באמצעות Bluetooth.

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

החיבור נוצר במלואו רק אם שני הצדדים אישרו זאת. אם אחת מהן או שתיהן נדחות, החיבור נמחק.

בדוגמאות שלמעלה מוצג החיבור שמאושר אוטומטית על ידי שני הצדדים, אבל בהתאם לתרחיש לדוגמה שלכם, ייתכן שתרצו להציג את האפשרות הזו למשתמשים באופן כלשהו.