importNearbyConnectionsclassExample{letconnectionManager:ConnectionManagerinit(){connectionManager=ConnectionManager(serviceID:"com.example.app",strategy:.cluster)connectionManager.delegate=self}}extensionExample:ConnectionManagerDelegate{funcconnectionManager(_connectionManager:ConnectionManager,didReceiveverificationCode:String,fromendpointID: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)}funcconnectionManager(_connectionManager:ConnectionManager,didReceivedata:Data,withIDpayloadID:PayloadID,fromendpointID:EndpointID){// A simple byte payload has been received. This will always include the full data.}funcconnectionManager(_connectionManager:ConnectionManager,didReceivestream:InputStream,withIDpayloadID:PayloadID,fromendpointID:EndpointID,cancellationTokentoken:CancellationToken){// We have received a readable stream.}funcconnectionManager(_connectionManager:ConnectionManager,didStartReceivingResourceWithIDpayloadID:PayloadID,fromendpointID:EndpointID,atlocalURL:URL,withNamename:String,cancellationTokentoken:CancellationToken){// We have started receiving a file. We will receive a separate transfer update// event when complete.}funcconnectionManager(_connectionManager:ConnectionManager,didReceiveTransferUpdateupdate:TransferUpdate,fromendpointID:EndpointID,forPayloadpayloadID:PayloadID){// A success, failure, cancelation or progress update.}funcconnectionManager(_connectionManager:ConnectionManager,didChangeTostate:ConnectionState,forendpointID:EndpointID){switchstate{case.connecting:// A connection to the remote endpoint is currently being established.case.connected:// We're connected! Can now start sending and receiving data.case.disconnected:// We've been disconnected from this endpoint. No more data can be sent or received.case.rejected:// The connection was rejected by one or both sides.}}}
importNearbyConnectionsclassExample{letconnectionManager:ConnectionManagerletadvertiser:Advertiserinit(){connectionManager=ConnectionManager(serviceID:"com.example.app",strategy:.cluster)connectionManager.delegate=selfadvertiser=Advertiser(connectionManager:connectionManager)advertiser.delegate=self// The endpoint info can be used to provide arbitrary information to the// discovering device (e.g. device name or type).advertiser.startAdvertising(using:"My Device".data(using:.utf8)!)}}extensionExample:AdvertiserDelegate{funcadvertiser(_advertiser:Advertiser,didReceiveConnectionRequestFromendpointID:EndpointID,withcontext:Data,connectionRequestHandler:@escaping(Bool)->Void){// Accept or reject any incoming connection requests. The connection will still need to// be verified in the connection manager delegate.connectionRequestHandler(true)}}
开始发现
如需开始发现,请初始化发现器,实现其委托方法,
然后调用 startDiscovery()。
Swift
importNearbyConnectionsclassExample{letconnectionManager:ConnectionManagerletdiscoverer:Discovererinit(){connectionManager=ConnectionManager(serviceID:"com.example.app",strategy:.cluster)connectionManager.delegate=selfdiscoverer=Discoverer(connectionManager:connectionManager)discoverer.delegate=selfdiscoverer.startDiscovery()}}extensionExample:DiscovererDelegate{funcdiscoverer(_discoverer:Discoverer,didFindendpointID:EndpointID,withcontext:Data){// An endpoint was found.}funcdiscoverer(_discoverer:Discoverer,didLoseendpointID:EndpointID){// A previously discovered endpoint has gone away.}}
[null,null,["最后更新时间 (UTC):2025-08-13。"],[[["\u003cp\u003eThe Connection Manager handles connection events and data transfer between devices, requiring a unique service ID and a chosen strategy for connection topology.\u003c/p\u003e\n"],["\u003cp\u003eTo advertise, initialize the advertiser, implement its delegate, and start advertising with endpoint information; to discover, initialize the discoverer, implement its delegate, and start discovery to find and connect with other devices.\u003c/p\u003e\n"],["\u003cp\u003eImplement delegate methods for the Connection Manager, Advertiser, and Discoverer to handle events like connection requests, data reception, and connection state changes, enabling communication and data exchange between devices.\u003c/p\u003e\n"],["\u003cp\u003eConsider stopping discovery once desired peers are found to reduce radio operations and potential connection disruptions, noting that previously discovered endpoints can still be connected to even after stopping discovery.\u003c/p\u003e\n"]]],[],null,["# Advertise and Discover\n\nSet up the Connection Manager\n-----------------------------\n\nThe connection manager handles all connection events and is the interface for\ntransferring data between devices. It is a requirement for both advertisement\nand discovery.\n\nFirst, A service ID should be chosen to uniquely identify your app. As a best\npractice, use the package name of your app (for example, `com.example.app`).\n\nNext, [choose a strategy](/nearby/connections/strategies) for your use case. The\nstrategy you select determines the connection topology for your app (`.cluster`,\n`.star` `.pointToPoint`).\n\nInitialize the connection manager and implement its delegate methods: \n\n### Swift\n\n import NearbyConnections\n\n class Example {\n let connectionManager: ConnectionManager\n\n init() {\n connectionManager = ConnectionManager(serviceID: \"com.example.app\", strategy: .cluster)\n connectionManager.delegate = self\n }\n }\n\n extension Example: ConnectionManagerDelegate {\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceive verificationCode: String,\n from endpointID: EndpointID, verificationHandler: @escaping (Bool) -\u003e Void) {\n // Optionally show the user the verification code. Your app should call this handler\n // with a value of `true` if the nearby endpoint should be trusted, or `false`\n // otherwise.\n verificationHandler(true)\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceive data: Data,\n withID payloadID: PayloadID, from endpointID: EndpointID) {\n // A simple byte payload has been received. This will always include the full data.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceive stream: InputStream,\n withID payloadID: PayloadID, from endpointID: EndpointID,\n cancellationToken token: CancellationToken) {\n // We have received a readable stream.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager,\n didStartReceivingResourceWithID payloadID: PayloadID,\n from endpointID: EndpointID, at localURL: URL,\n withName name: String, cancellationToken token: CancellationToken) {\n // We have started receiving a file. We will receive a separate transfer update\n // event when complete.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager,\n didReceiveTransferUpdate update: TransferUpdate,\n from endpointID: EndpointID, forPayload payloadID: PayloadID) {\n // A success, failure, cancelation or progress update.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didChangeTo state: ConnectionState,\n for endpointID: EndpointID) {\n switch state {\n case .connecting:\n // A connection to the remote endpoint is currently being established.\n case .connected:\n // We're connected! Can now start sending and receiving data.\n case .disconnected:\n // We've been disconnected from this endpoint. No more data can be sent or received.\n case .rejected:\n // The connection was rejected by one or both sides.\n }\n }\n }\n\nStart Advertising\n-----------------\n\nTo start advertising, initialize the advertiser, implement its delegate methods,\nand make a call to `startAdvertising(using:)`. \n\n### Swift\n\n import NearbyConnections\n\n class Example {\n let connectionManager: ConnectionManager\n let advertiser: Advertiser\n\n init() {\n connectionManager = ConnectionManager(serviceID: \"com.example.app\", strategy: .cluster)\n connectionManager.delegate = self\n\n advertiser = Advertiser(connectionManager: connectionManager)\n advertiser.delegate = self\n\n // The endpoint info can be used to provide arbitrary information to the\n // discovering device (e.g. device name or type).\n advertiser.startAdvertising(using: \"My Device\".data(using: .utf8)!)\n }\n }\n\n extension Example: AdvertiserDelegate {\n func advertiser(\n _ advertiser: Advertiser, didReceiveConnectionRequestFrom endpointID: EndpointID,\n with context: Data, connectionRequestHandler: @escaping (Bool) -\u003e Void) {\n // Accept or reject any incoming connection requests. The connection will still need to\n // be verified in the connection manager delegate.\n connectionRequestHandler(true)\n }\n }\n\nStart Discovery\n---------------\n\nTo start discovering, initialize the discoverer, implement its delegate methods,\nand make a call to `startDiscovery()`. \n\n### Swift\n\n import NearbyConnections\n\n class Example {\n let connectionManager: ConnectionManager\n let discoverer: Discoverer\n\n init() {\n connectionManager = ConnectionManager(serviceID: \"com.example.app\", strategy: .cluster)\n connectionManager.delegate = self\n\n discoverer = Discoverer(connectionManager: connectionManager)\n discoverer.delegate = self\n\n discoverer.startDiscovery()\n }\n }\n\n extension Example: DiscovererDelegate {\n func discoverer(\n _ discoverer: Discoverer, didFind endpointID: EndpointID, with context: Data) {\n // An endpoint was found.\n }\n\n func discoverer(_ discoverer: Discoverer, didLose endpointID: EndpointID) {\n // A previously discovered endpoint has gone away.\n }\n }\n\n| **Note:** After calling `stopDiscovery()`, the discoverer can still request connections to advertisers that were discovered; however, the discoverer will not discover any new advertisers until it starts discovery again.\n| **Caution:** Since most forms of discovery entail heavy radio operations that increase the odds of established connections getting broken, a very common pattern is to invoke `stopDiscovery()` once you find all the peers you want to connect to and exchange data with."]]