Thiết lập
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Vui lòng tham khảo phần Kết nối lân cận để biết cách thiết lập tính năng Kết nối lân cận.
Tin nhắn ngắn
Nearby Connections cho phép ứng dụng gửi dữ liệu trong vòng 131 byte mà không cần thiết lập kết nối với thiết bị từ xa. Vui lòng tham khảo quy trình bên dưới để biết cách chuyển tin nhắn trong phạm vi 131 byte.
Nhà xuất bản
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()
}
}
Người đăng ký
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.
}
}
Tin nhắn dài
Đối với các tin nhắn lớn hơn 131 byte, bạn cần thiết lập kết nối giữa các thiết bị để chuyển tin nhắn. Vui lòng tham khảo quy trình bên dưới để biết cách chuyển dữ liệu lớn bằng tính năng Kết nối lân cận.
Nhà xuất bản
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)
}
}
Người đăng ký
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.
}
}
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2025-08-29 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-29 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 }"]]