建立連線
一旦找到附近的裝置,尋找人員即可建立連線。以下範例會在偵測到裝置後立即要求裝置連線。
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)
}
}
在兩端都已接受連線時,兩者才建立完成。如果兩者皆遭拒,系統就會捨棄連線。
上例顯示雙方兩側接受的連線,但根據您的用途,您可能會想以某種方式向使用者提供這個選項。