Stay organized with collections
Save and categorize content based on your preferences.
Please refer to Nearby Connections about how to setup Nearby Connections.
Short Messages
Nearby Connections allows its clients to send data within 131 bytes without establishing a connection to the remote device. Please refer to the flow below as how to transfer messages within 131 bytes.
For messages which are larger than 131 bytes, a connection between the devices needs to be established to transfer the message. Please refer to the flow below as how to transfer large data using Nearby Connections.
Publisher
classPublisher{letconnectionManager:ConnectionManagerletadvertiser:Advertiserinit(){connectionManager=ConnectionManager(serviceID:<SERVICE_ID>,strategy:.pointToPoint)connectionManager.delegate=selfadvertiser=Advertiser(connectionManager:connectionManager)advertiser.delegate=self}funcstartPublishing(){advertiser.startAdvertising(using:<ENDPOINT_INFO>)}funcstopPublishing(){advertiser.stopAdvertising()}}extensionPublisher:ConnectionManagerDelegate{funcconnectionManager(_connectionManager:ConnectionManager,didReceivedata:Data,withIDpayloadID:PayloadID,fromendpointID:EndpointID){//Wecanignoreimplementation,becausewearethepublisher.}funcconnectionManager(_connectionManager:ConnectionManager,didReceivestream:InputStream,withIDpayloadID:PayloadID,fromendpointID:EndpointID,cancellationTokentoken:CancellationToken){//Wecanignoreimplementation,becausewearethepublisher.}funcconnectionManager(_connectionManager:ConnectionManager,didStartReceivingResourceWithIDpayloadID:PayloadID,fromendpointID:EndpointID,atlocalURL:URL,withNamename:String,cancellationTokentoken:CancellationToken){//Wecanignoreimplementation,becausewearethepublisher.}funcconnectionManager(_connectionManager:ConnectionManager,didReceiveTransferUpdateupdate:TransferUpdate,fromendpointID:EndpointID,forPayloadpayloadID:PayloadID){//Wecanignoreimplementation,becausewearethepublisher.}funcconnectionManager(_connectionManager:ConnectionManager,didChangeTostate:ConnectionState,forendpointID:EndpointID){switchstate{case.connecting://Aconnectiontotheremoteendpointiscurrentlybeingestablished.case.connected://We're connected! Can now start sending and receiving data. connectionManager.send(<MESSAGE_DATA>, to: [endpointID]) case .disconnected: // We'vebeendisconnectedfromthisendpoint.Nomoredatacanbesentorreceived.case.rejected://Theconnectionwasrejectedbyoneorbothsides.}}}extensionPublisher:AdvertiserDelegate{funcadvertiser(_advertiser:Advertiser,didReceiveConnectionRequestFromendpointID:EndpointID,withcontext:Data,connectionRequestHandler:@escaping(Bool)->Void){//Automaticallyacceptanyincomingconnectionrequests.connectionRequestHandler(true)}}
Subscriber
classSubscriber{letconnectionManager:ConnectionManagerletdiscoverer:Discovererinit(){connectionManager=ConnectionManager(serviceID:<SERVICE_ID>,strategy:.pointToPoint)connectionManager.delegate=selfdiscoverer=Discoverer(connectionManager:connectionManager)discoverer.delegate=self}funcstartSubscription(){discoverer.startDiscovery()}funcstopSubscription(){discoverer.stopDiscovery()}}extensionSubscriber:ConnectionManagerDelegate{funcconnectionManager(_connectionManager:ConnectionManager,didReceivedata:Data,withIDpayloadID:PayloadID,fromendpointID:EndpointID){//Thisalwaysgetsthefulldataofthepayload.print(data)}funcconnectionManager(_connectionManager:ConnectionManager,didReceivestream:InputStream,withIDpayloadID:PayloadID,fromendpointID:EndpointID,cancellationTokentoken:CancellationToken){//Wecanignoreimplementationbecauseweonlycareaboutbytespayloads.}funcconnectionManager(_connectionManager:ConnectionManager,didStartReceivingResourceWithIDpayloadID:PayloadID,fromendpointID:EndpointID,atlocalURL:URL,withNamename:String,cancellationTokentoken:CancellationToken){//Wecanignoreimplementationbecauseweonlycareaboutbytespayloads.}funcconnectionManager(_connectionManager:ConnectionManager,didReceiveTransferUpdateupdate:TransferUpdate,fromendpointID:EndpointID,forPayloadpayloadID:PayloadID){//Bytespayloadsaresentasasinglechunk,soyou'll receive TransferUpdate.success//immediately.}funcconnectionManager(_connectionManager:ConnectionManager,didChangeTostate:ConnectionState,forendpointID:EndpointID){switchstate{case.connecting://Aconnectiontotheremoteendpointiscurrentlybeingestablished.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://Theconnectionwasrejectedbyoneorbothsides.}}}extensionSubscriber:DiscovererDelegate{funcdiscoverer(_discoverer:Discoverer,didFindendpointID:EndpointID,withcontext:Data){//Anendpointwasfound.Werequestaconnectiontoit.discoverer.requestConnection(to:endpointID,using:<ENDPOINT_INFO>)}funcdiscoverer(_discoverer:Discoverer,didLoseendpointID:EndpointID){//Apreviouslydiscoveredendpointhasgoneaway.}}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-14 UTC."],[[["\u003cp\u003eNearby Connections enables communication between nearby devices using Bluetooth, Wi-Fi, and peer-to-peer connections.\u003c/p\u003e\n"],["\u003cp\u003eShort messages (under 131 bytes) can be sent without establishing a connection, ideal for lightweight data exchange.\u003c/p\u003e\n"],["\u003cp\u003eLong messages (over 131 bytes) require a connection for reliable transfer, supporting various data types and sizes.\u003c/p\u003e\n"],["\u003cp\u003eBoth publishers and subscribers need a shared service ID for successful discovery and connection establishment.\u003c/p\u003e\n"],["\u003cp\u003eConnection lifecycle includes advertising, discovery, connection request, data transfer, and disconnection states.\u003c/p\u003e\n"]]],["Nearby Connections facilitates data transfer, with different procedures for short (≤131 bytes) and long messages. For short messages, the publisher uses an `Advertiser` to broadcast `MESSAGE_DATA`, while the subscriber utilizes a `Discoverer` to find and receive this data. For long messages, publishers advertise `ENDPOINT_INFO` and accept incoming connection requests. Subscribers discover endpoints and request connections, enabling the exchange of `MESSAGE_DATA` once a `connected` state is established between the devices.\n"],null,["# Setup\n\nPlease refer to [Nearby Connections](//developers.google.com/nearby/connections/swift/get-started) about how to setup Nearby Connections.\n\nShort Messages\n==============\n\nNearby Connections allows its clients to send data within 131 bytes without establishing a connection to the remote device. Please refer to the flow below as how to transfer messages within 131 bytes.\n\nPublisher\n---------\n\n class Publisher {\n let connectionManager: ConnectionManager\n let advertiser: Advertiser\n\n init() {\n connectionManager = ConnectionManager(serviceID: \u003cSERVICE_ID\u003e, strategy: .pointToPoint)\n advertiser = Advertiser(connectionManager: connectionManager)\n }\n\n func startPublishing() {\n advertiser.startAdvertising(using: \u003cMESSAGE_DATA\u003e)\n }\n\n func stopPublishing() {\n advertiser.stopAdvertising()\n }\n }\n\nSubscriber\n----------\n\n class Subscriber {\n let connectionManager: ConnectionManager\n let discoverer: Discoverer\n\n init() {\n connectionManager = ConnectionManager(serviceID: \u003cSERVICE_ID\u003e, strategy: .pointToPoint)\n\n discoverer = Discoverer(connectionManager: connectionManager)\n discoverer.delegate = self\n }\n\n func startSubscription() {\n discoverer.startDiscovery()\n }\n\n func stopSubscription() {\n discoverer.stopDiscovery()\n }\n }\n\n extension Subscriber: DiscovererDelegate {\n func discoverer(_ discoverer: Discoverer, didFind endpointID: EndpointID, with context: Data) {\n // A remote advertising endpoint is found.\n print(context) // `context` is the published message data.\n }\n\n func discoverer(_ discoverer: Discoverer, didLose endpointID: EndpointID) {\n // A previously discovered endpoint has gone away.\n }\n }\n\nLong Messages\n=============\n\nFor messages which are larger than 131 bytes, a connection between the devices needs to be established to transfer the message. Please refer to the flow below as how to transfer large data using Nearby Connections.\n\nPublisher\n---------\n\n class Publisher {\n let connectionManager: ConnectionManager\n let advertiser: Advertiser\n\n init() {\n connectionManager = ConnectionManager(serviceID: \u003cSERVICE_ID\u003e, strategy: .pointToPoint)\n connectionManager.delegate = self\n\n advertiser = Advertiser(connectionManager: connectionManager)\n advertiser.delegate = self\n }\n\n func startPublishing() {\n advertiser.startAdvertising(using: \u003cENDPOINT_INFO\u003e)\n }\n\n func stopPublishing() {\n advertiser.stopAdvertising()\n }\n }\n\n extension Publisher: ConnectionManagerDelegate {\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceive data: Data, withID payloadID: PayloadID,\n from endpointID: EndpointID) {\n // We can ignore implementation, because we are the publisher.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceive stream: InputStream,\n withID payloadID: PayloadID,\n from endpointID: EndpointID, cancellationToken token: CancellationToken) {\n // We can ignore implementation, because we are the publisher.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didStartReceivingResourceWithID payloadID: PayloadID,\n from endpointID: EndpointID, at localURL: URL, withName name: String,\n cancellationToken token: CancellationToken) {\n // We can ignore implementation, because we are the publisher.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceiveTransferUpdate update: TransferUpdate,\n from endpointID: EndpointID, forPayload payloadID: PayloadID) {\n // We can ignore implementation, because we are the publisher.\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 connectionManager.send(\u003cMESSAGE_DATA\u003e, to: [endpointID])\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\n extension Publisher: AdvertiserDelegate {\n func advertiser(\n _ advertiser: Advertiser, didReceiveConnectionRequestFrom endpointID: EndpointID,\n with context: Data, connectionRequestHandler: @escaping (Bool) -\u003e Void) {\n // Automatically accept any incoming connection requests.\n connectionRequestHandler(true)\n }\n }\n\nSubscriber\n----------\n\n class Subscriber {\n let connectionManager: ConnectionManager\n let discoverer: Discoverer\n\n init() {\n connectionManager = ConnectionManager(serviceID: \u003cSERVICE_ID\u003e, strategy: .pointToPoint)\n connectionManager.delegate = self\n\n discoverer = Discoverer(connectionManager: connectionManager)\n discoverer.delegate = self\n }\n\n func startSubscription() {\n discoverer.startDiscovery()\n }\n\n func stopSubscription() {\n discoverer.stopDiscovery()\n }\n }\n\n extension Subscriber: ConnectionManagerDelegate {\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceive data: Data, withID payloadID: PayloadID,\n from endpointID: EndpointID) {\n // This always gets the full data of the payload.\n print(data)\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceive stream: InputStream,\n withID payloadID: PayloadID,\n from endpointID: EndpointID, cancellationToken token: CancellationToken) {\n // We can ignore implementation because we only care about bytes payloads.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didStartReceivingResourceWithID payloadID: PayloadID,\n from endpointID: EndpointID, at localURL: URL, withName name: String,\n cancellationToken token: CancellationToken) {\n // We can ignore implementation because we only care about bytes payloads.\n }\n\n func connectionManager(\n _ connectionManager: ConnectionManager, didReceiveTransferUpdate update: TransferUpdate,\n from endpointID: EndpointID, forPayload payloadID: PayloadID) {\n // Bytes payloads are sent as a single chunk, so you'll receive TransferUpdate.success\n // immediately.\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\n extension Subscriber: DiscovererDelegate {\n func discoverer(_ discoverer: Discoverer, didFind endpointID: EndpointID, with context: Data) {\n // An endpoint was found. We request a connection to it.\n discoverer.requestConnection(to: endpointID, using: \u003cENDPOINT_INFO\u003e)\n }\n\n func discoverer(_ discoverer: Discoverer, didLose endpointID: EndpointID) {\n // A previously discovered endpoint has gone away.\n }\n }"]]