建立連線
當找到鄰近裝置時,探索人員可以啟動連線。 以下範例會在裝置當機後,立即要求與裝置連線 發現。
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)
}
}
只有在雙方都接受的情況下,連線才會建立完成。如果有 或兩者皆拒絕時,系統會捨棄連線。
上面的例子顯示兩者都能自動接受連線 根據您的用途,建議您根據用途 以某種方式對使用者來說