设置
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
如需了解如何设置“附近的连接”,请参阅附近的连接。
短消息
借助附近连接,客户端无需与远程设备建立连接,即可发送 131 字节以内的数据。如需了解如何在 131 字节内传输消息,请参阅以下流程。
发布商
class Publisher {
let connectionManager: ConnectionManager
let advertiser: Advertiser
init() {
connectionManager = ConnectionManager(serviceID: <SERVICE_ID>, strategy: .pointToPoint)
advertiser = Advertiser(connectionManager: connectionManager)
}
func startPublishing() {
advertiser.startAdvertising(using: <MESSAGE_DATA>)
}
func stopPublishing() {
advertiser.stopAdvertising()
}
}
订阅者
class Subscriber {
let connectionManager: ConnectionManager
let discoverer: Discoverer
init() {
connectionManager = ConnectionManager(serviceID: <SERVICE_ID>, strategy: .pointToPoint)
discoverer = Discoverer(connectionManager: connectionManager)
discoverer.delegate = self
}
func startSubscription() {
discoverer.startDiscovery()
}
func stopSubscription() {
discoverer.stopDiscovery()
}
}
extension Subscriber: DiscovererDelegate {
func discoverer(_ discoverer: Discoverer, didFind endpointID: EndpointID, with context: Data) {
// A remote advertising endpoint is found.
print(context) // `context` is the published message data.
}
func discoverer(_ discoverer: Discoverer, didLose endpointID: EndpointID) {
// A previously discovered endpoint has gone away.
}
}
长消息
对于大于 131 个字节的消息,需要在设备之间建立连接才能传输消息。如需了解如何使用附近分享功能传输大量数据,请参阅以下流程。
发布商
class Publisher {
let connectionManager: ConnectionManager
let advertiser: Advertiser
init() {
connectionManager = ConnectionManager(serviceID: <SERVICE_ID>, strategy: .pointToPoint)
connectionManager.delegate = self
advertiser = Advertiser(connectionManager: connectionManager)
advertiser.delegate = self
}
func startPublishing() {
advertiser.startAdvertising(using: <ENDPOINT_INFO>)
}
func stopPublishing() {
advertiser.stopAdvertising()
}
}
extension Publisher: ConnectionManagerDelegate {
func connectionManager(
_ connectionManager: ConnectionManager, didReceive data: Data, withID payloadID: PayloadID,
from endpointID: EndpointID) {
// We can ignore implementation, because we are the publisher.
}
func connectionManager(
_ connectionManager: ConnectionManager, didReceive stream: InputStream,
withID payloadID: PayloadID,
from endpointID: EndpointID, cancellationToken token: CancellationToken) {
// We can ignore implementation, because we are the publisher.
}
func connectionManager(
_ connectionManager: ConnectionManager, didStartReceivingResourceWithID payloadID: PayloadID,
from endpointID: EndpointID, at localURL: URL, withName name: String,
cancellationToken token: CancellationToken) {
// We can ignore implementation, because we are the publisher.
}
func connectionManager(
_ connectionManager: ConnectionManager, didReceiveTransferUpdate update: TransferUpdate,
from endpointID: EndpointID, forPayload payloadID: PayloadID) {
// We can ignore implementation, because we are the publisher.
}
func connectionManager(
_ connectionManager: ConnectionManager, didChangeTo state: ConnectionState,
for endpointID: EndpointID) {
switch state {
case .connecting:
// A connection to the remote endpoint is currently being established.
case .connected:
// We're connected! Can now start sending and receiving data.
connectionManager.send(<MESSAGE_DATA>, to: [endpointID])
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.
}
}
}
extension Publisher: AdvertiserDelegate {
func advertiser(
_ advertiser: Advertiser, didReceiveConnectionRequestFrom endpointID: EndpointID,
with context: Data, connectionRequestHandler: @escaping (Bool) -> Void) {
// Automatically accept any incoming connection requests.
connectionRequestHandler(true)
}
}
订阅者
class Subscriber {
let connectionManager: ConnectionManager
let discoverer: Discoverer
init() {
connectionManager = ConnectionManager(serviceID: <SERVICE_ID>, strategy: .pointToPoint)
connectionManager.delegate = self
discoverer = Discoverer(connectionManager: connectionManager)
discoverer.delegate = self
}
func startSubscription() {
discoverer.startDiscovery()
}
func stopSubscription() {
discoverer.stopDiscovery()
}
}
extension Subscriber: ConnectionManagerDelegate {
func connectionManager(
_ connectionManager: ConnectionManager, didReceive data: Data, withID payloadID: PayloadID,
from endpointID: EndpointID) {
// This always gets the full data of the payload.
print(data)
}
func connectionManager(
_ connectionManager: ConnectionManager, didReceive stream: InputStream,
withID payloadID: PayloadID,
from endpointID: EndpointID, cancellationToken token: CancellationToken) {
// We can ignore implementation because we only care about bytes payloads.
}
func connectionManager(
_ connectionManager: ConnectionManager, didStartReceivingResourceWithID payloadID: PayloadID,
from endpointID: EndpointID, at localURL: URL, withName name: String,
cancellationToken token: CancellationToken) {
// We can ignore implementation because we only care about bytes payloads.
}
func connectionManager(
_ connectionManager: ConnectionManager, didReceiveTransferUpdate update: TransferUpdate,
from endpointID: EndpointID, forPayload payloadID: PayloadID) {
// Bytes payloads are sent as a single chunk, so you'll receive TransferUpdate.success
// immediately.
}
func connectionManager(
_ connectionManager: ConnectionManager, didChangeTo state: ConnectionState,
for endpointID: EndpointID) {
switch state {
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.
}
}
}
extension Subscriber: DiscovererDelegate {
func discoverer(_ discoverer: Discoverer, didFind endpointID: EndpointID, with context: Data) {
// An endpoint was found. We request a connection to it.
discoverer.requestConnection(to: endpointID, using: <ENDPOINT_INFO>)
}
func discoverer(_ discoverer: Discoverer, didLose endpointID: EndpointID) {
// A previously discovered endpoint has gone away.
}
}
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-29。
[null,null,["最后更新时间 (UTC):2025-08-29。"],[[["\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 }"]]