建立連線
找到鄰近裝置後,探索者可以啟動連線。以下範例會在發現裝置後立即要求連線。
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)
}
}
雙方都接受後,連結才會完全建立。如果其中一方或雙方拒絕,連線就會遭到捨棄。
上述範例顯示雙方自動接受連線,但視您的用途而定,您可能希望以某種方式向使用者顯示這個選項。