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