General:
TN3151 Choosing the right networking API
Networking Overview document — Despite the fact that this is in the archive, this is still really useful.
TLS for App Developers DevForums post
Choosing a Network Debugging Tool documentation
WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi?
TN3135 Low-level networking on watchOS
Adapt to changing network conditions tech talk
Foundation networking:
DevForums tags: Foundation, CFNetwork
URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms.
Network framework:
DevForums tag: Network
Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms.
Moving from Multipeer Connectivity to Network Framework DevForums post
Network Extension (including Wi-Fi on iOS):
See Network Extension Resources
Wi-Fi Fundamentals
Wi-Fi on macOS:
DevForums tag: Core WLAN
Core WLAN framework documentation
Wi-Fi Fundamentals
Secure networking:
DevForums tags: Security
Apple Platform Security support document
Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS).
Available trusted root certificates for Apple operating systems support article
Requirements for trusted certificates in iOS 13 and macOS 10.15 support article
About upcoming limits on trusted certificates support article
Apple’s Certificate Transparency policy support article
Technote 2232 HTTPS Server Trust Evaluation
Technote 2326 Creating Certificates for TLS Testing
QA1948 HTTPS and Test Servers
Miscellaneous:
More network-related DevForums tags: 5G, QUIC, Bonjour
On FTP DevForums post
Using the Multicast Networking Additional Capability DevForums post
Investigating Network Latency Problems DevForums post
Local Network Privacy FAQ DevForums post
Extra-ordinary Networking DevForums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Network
RSS for tagNetwork connections send and receive data using transport and security protocols.
Posts under Network tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
In TN3179 under "macOS considerations" there are a set of instances where local network privacy does not apply:
macOS automatically allows local network access by:
Any daemon started by launchd
Any program running as root
Command-line tools run from Terminal or over SSH, including any child processes they spawn
I am running some tests in my app that use the local network, attempting to run them from both the terminal app and from a VScode terminal and I am getting permissions prompts. After allowing these pop ups, some of the tests still fail as if networking was blocked.
I was trying to call getsockopt(fd, SOL_LOCAL, LOCAL_PEERCRED, ...), and by mistake passed a wrong value for the second parameter where it should be SOL_LOCAL. But the call still succeeded. Then I did more experiments and passed more random values for the second parameter, all succeeded. It seems there is a lack of parameter check in the implementation of getsockopt() , where it should return errors if people pass invalid parameters instead of succeeding silently. Hope the Apple engineers can help to validate and fix it.
Hi
we want to use CONNECT-IP extension within the MASQUE protocol suite.
we want to be able to reroute ICMP packets from our machine and redirect them to our MASQUE proxy.
we want to avoid a creation of virtual interface or modifying the routing tables.
is it possible, if so, how can it be achieved.
thanks
I'm facing an issue where if a WiFi network is turned off and back on within a short time frame (2-4 seconds), iOS still shows the device as connected but does not send a new DHCP request. This causes a problem for my network device, which relies on the DHCP request to assign an IP address. Without the request, the device is unable to establish a socket connection properly.
Is there any way to force iOS to send a DHCP request immediately when reconnecting to the network in this scenario? Are there any known workarounds or configurations that might help ensure the DHCP process is re-triggered?
Any insights would be appreciated. Thanks!
We've observed intermittent crashes in our production environment, pls help to take a look at this, thx
I see a lot of folks spend a lot of time trying to get Multipeer Connectivity to work for them. My experience is that the final result is often unsatisfactory. Instead, my medium-to-long term recommendation is to use Network framework instead. This post explains how you might move from Multipeer Connectivity to Network framework.
If you have questions or comments, put them in a new thread. Place it in the App & System Services > Networking topic area and tag it with Multipeer Connectivity and Network framework.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Moving from Multipeer Connectivity to Network Framework
Multipeer Connectivity has a number of drawbacks:
It has an opinionated networking model, where every participant in a session is a symmetric peer. Many apps work better with the traditional client/server model.
It offers good latency but poor throughput.
It doesn’t support flow control, aka back pressure, which severely constrains its utility for general-purpose networking.
It includes a number of UI components that are effectively obsolete.
It hasn’t evolved in recent years. For example, it relies on NSStream, which has been scheduled for deprecation as far as networking is concerned.
It always enables peer-to-peer Wi-Fi, something that’s not required for many apps and can impact the performance of the network (see Enable peer-to-peer Wi-Fi, below, for more about this).
Its security model requires the use of PKI — public key infrastructure, that is, digital identities and certificates — which are tricky to deploy in a peer-to-peer environment.
It has some gnarly bugs.
IMPORTANT Many folks use Multipeer Connectivity because they think it’s the only way to use peer-to-peer Wi-Fi. That’s not the case. Network framework has opt-in peer-to-peer Wi-Fi support. See Enable peer-to-peer Wi-Fi, below.
If Multipeer Connectivity is not working well for you, consider moving to Network framework. This post explains how to do that in 13 easy steps (-:
Plan for security
Select a network architecture
Create a peer identifier
Choose a protocol to match your send mode
Discover peers
Design for privacy
Configure your connections
Manage a listener
Manage a connection
Send and receive reliable messages
Send and receive best effort messages
Start a stream
Send a resource
Finally, at the end of the post you’ll find two appendices:
Final notes contains some general hints and tips.
Symbol cross reference maps symbols in the Multipeer Connectivity framework to sections of this post. Consult it if you’re not sure where to start with a specific Multipeer Connectivity construct.
Plan for security
The first thing you need to think about is security. Multipeer Connectivity offers three security models, expressed as choices in the MCEncryptionPreference enum:
.none for no security
.optional for optional security
.required for required security
For required security each peer must have a digital identity.
Optional security is largely pointless. It’s more complex than no security but doesn’t yield any benefits. So, in this post we’ll focus on the no security and required security models.
Your security choice affects the network protocols you can use:
QUIC is always secure.
WebSocket, TCP, and UDP can be used with and without TLS security.
QUIC security only supports PKI. TLS security supports both TLS-PKI and pre-shared key (PSK). You might find that TLS-PSK is easier to deploy in a peer-to-peer environment.
To configure the security of the QUIC protocol:
func quicParameters() -> NWParameters {
let quic = NWProtocolQUIC.Options(alpn: ["MyAPLN"])
let sec = quic.securityProtocolOptions
… configure `sec` here …
return NWParameters(quic: quic)
}
To enable TLS over TCP:
func tlsOverTCPParameters() -> NWParameters {
let tcp = NWProtocolTCP.Options()
let tls = NWProtocolTLS.Options()
let sec = tls.securityProtocolOptions
… configure `sec` here …
return NWParameters(tls: tls, tcp: tcp)
}
To enable TLS over UDP, also known as DTLS:
func dtlsOverUDPParameters() -> NWParameters {
let udp = NWProtocolUDP.Options()
let dtls = NWProtocolTLS.Options()
let sec = dtls.securityProtocolOptions
… configure `sec` here …
return NWParameters(dtls: dtls, udp: udp)
}
To configure TLS with a local digital identity and custom server trust evaluation:
func configureTLSPKI(sec: sec_protocol_options_t, identity: SecIdentity) {
let secIdentity = sec_identity_create(identity)!
sec_protocol_options_set_local_identity(sec, secIdentity)
if disableServerTrustEvaluation {
sec_protocol_options_set_verify_block(sec, { metadata, secTrust, completionHandler in
let trust = sec_trust_copy_ref(secTrust).takeRetainedValue()
… evaluate `trust` here …
completionHandler(true)
}, .main)
}
}
To configure TLS with a pre-shared key:
func configureTLSPSK(sec: sec_protocol_options_t, identity: Data, key: Data) {
let identityDD = identity.withUnsafeBytes { DispatchData(bytes: $0) }
let keyDD = identity.withUnsafeBytes { DispatchData(bytes: $0) }
sec_protocol_options_add_pre_shared_key(
sec,
keyDD as dispatch_data_t,
identityDD as dispatch_data_t
)
sec_protocol_options_append_tls_ciphersuite(
sec,
tls_ciphersuite_t(rawValue: TLS_PSK_WITH_AES_128_GCM_SHA256)!
)
}
Select a network architecture
Multipeer Connectivity uses a star network architecture. All peers are equal, and every peer is effectively connected to every peer. Many apps work better with the client/server model, where one peer acts on the server and all the others are clients. Network framework supports both models.
To implement a client/server network architecture with Network framework:
Designate one peer as the server and all the others as clients.
On the server, use NWListener to listen for incoming connections.
On each client, use NWConnection to made an outgoing connection to the server.
To implement a star network architecture with Network framework:
On each peer, start a listener.
And also start a connection to each of the other peers.
This is likely to generate a lot of redundant connections, as peer A connects to peer B and vice versa. You’ll need to a way to deduplicate those connections, which is the subject of the next section.
IMPORTANT While the star network architecture is more likely to create redundant connections, the client/server network architecture can generate redundant connections as well. The advice in the next section applies to both architectures.
Create a peer identifier
Multipeer Connectivity uses MCPeerID to uniquely identify each peer. There’s nothing particularly magic about MCPeerID; it’s effectively a wrapper around a large random number.
To identify each peer in Network framework, generate your own large random number. One good choice for a peer identifier is a locally generated UUID, created using the system UUID type.
Some Multipeer Connectivity apps persist their local MCPeerID value, taking advantage of its NSSecureCoding support. You can do the same with a UUID, using either its string representation or its Codable support.
IMPORTANT Before you decide to persist a peer identifier, think about the privacy implications. See Design for privacy below.
Avoid having multiple connections between peers; that’s both wasteful and potentially confusing. Use your peer identifier to deduplicate connections.
Deduplicating connections in a client/server network architecture is easy. Have each client check in with the server with its peer identifier. If the server already has a connection for that identifier, it can either close the old connection and keep the new connection, or vice versa.
Deduplicating connections in a star network architecture is a bit trickier. One option is to have each peer send its peer identifier to the other peer and then the peer with the ‘best’ identifier wins. For example, imagine that peer A makes an outgoing connection to peer B while peer B is simultaneously making an outgoing connection to peer A. When it receives the incoming connection, each peer compares its peer identifier to that of the other. If it’s peer identifier is larger, it drops the incoming connection, on the assumption that it’s outgoing connection will ‘win’.
Choose a protocol to match your send mode
Multipeer Connectivity offers two send modes, expressed as choices in the MCSessionSendDataMode enum:
.reliable for reliable messages
.unreliable for best effort messages
Best effort is useful when sending latency-sensitive data, that is, data where retransmission is pointless because, by the retransmission arrives, the data will no longer be relevant. This is common in audio and video applications.
In Network framework, the send mode is set by the connection’s protocol:
A specific QUIC connection is either reliable or best effort.
WebSocket and TCP are reliable.
UDP is best effort.
Start with a reliable connection. In many cases you can stop there, because you never need a best effort connection.
If you’re not sure which reliable protocol to use, choose WebSocket. It has key advantages over other protocols:
It supports both security models: none and required. Moreover, its required security model supports both TLS-PKI and TLS PSK. In contrast, QUIC only supports the required security model, and within that model it only supports TLS-PKI.
It allows you to send messages over the connection. In contrast, TCP works in terms of bytes, meaning that you have to add your own framing.
If you need a best effort connection, get started with a reliable connection and use that connection to set up a parallel best effort connection. For example, you might have an exchange like this:
Peer A uses its reliable WebSocket connection to peer B to send a request for a parallel best effort UDP connection.
Peer B receives that, opens a UDP listener, and sends the UDP listener’s port number back to peer A.
Peer A opens its parallel UDP connection to that port on peer B.
Note For step 3, get peer B’s IP address from the currentPath property of the reliable WebSocket connection.
If you’re not sure which best effort protocol to use, use UDP. While it is possible to use QUIC in datagram mode, it has the same security complexities as QUIC in reliable mode.
Discover peers
Multipeer Connectivity has a types for advertising a peer’s session (MCAdvertiserAssistant) and a type for browsering for peer (MCNearbyServiceBrowser).
In Network framework, configure the listener to advertise its service by setting the service property of NWListener:
let listener: NWListener = …
listener.service = .init(type: "_example._tcp")
listener.serviceRegistrationUpdateHandler = { change in
switch change {
case .add(let endpoint):
… update UI for the added listener endpoint …
break
case .remove(let endpoint):
… update UI for the removed listener endpoint …
break
@unknown default:
break
}
}
listener.stateUpdateHandler = … handle state changes …
listener.newConnectionHandler = … handle the new connection …
listener.start(queue: .main)
This example also shows how to use the serviceRegistrationUpdateHandler to update your UI to reflect changes in the listener.
Note This example uses a service type of _example._tcp. See About service types, below, for more details on that.
To browse for services, use NWBrowser:
let browser = NWBrowser(for: .bonjour(type: "_example._tcp", domain: nil), using: .tcp)
browser.browseResultsChangedHandler = { latestResults, _ in
… update UI to show the latest results …
}
browser.stateUpdateHandler = … handle state changes …
browser.start(queue: .main)
This yields NWEndpoint values for each peer that it discovers. To connect to a given peer, create an NWConnection with that endpoint.
About service types
The examples in this post use _example._tcp for the service type. The first part, _example, is directly analogous to the serviceType value you supply when creating MCAdvertiserAssistant and MCNearbyServiceBrowser objects. The second part is either _tcp or _udp depending on the underlying transport protocol. For TCP and WebSocket, use _tcp. For UDP and QUIC, use _udp.
Service types are described in RFC 6335. If you deploy an app that uses a new service type, register taht service type with IANA.
Discovery UI
Multipeer Connectivity also has UI components for advertising (MCNearbyServiceAdvertiser) and browsing (MCBrowserViewController). There’s no direct equivalent to this in Network framework. Instead, use your preferred UI framework to create a UI that best suits your requirements.
Discovery TXT records
The Bonjour service discovery protocol used by Network framework supports TXT records. Using these, a listener can associate metadata with its service and a browser can get that metadata for each discovered service.
To advertise a TXT record with your listener, include it it the service property value:
let listener: NWListener = …
let peerID: UUID = …
var txtRecord = NWTXTRecord()
txtRecord["peerID"] = peerID.uuidString
listener.service = .init(type: "_example._tcp", txtRecord: txtRecord.data)
To browse for services and their associated TXT records, use the .bonjourWithTXTRecord(…) descriptor:
let browser = NWBrowser(for: .bonjourWithTXTRecord(type: "_example._tcp", domain: nil), using: .tcp)
browser.browseResultsChangedHandler = { latestResults, _ in
for result in latestResults {
guard
case .bonjour(let txtRecord) = result.metadata,
let peerID = txtRecord["peerID"]
else { continue }
// … examine `result` and `peerID` …
_ = peerID
}
}
This example includes the peer identifier in the TXT record with the goal of reducing the number of duplicate connections, but that’s just one potential use for TXT records.
Design for privacy
This section lists some privacy topics to consider as you implement your app. Obviously this isn’t an exhaustive list. For general advice on this topic, see Protecting the User’s Privacy.
There can be no privacy without security. If you didn’t opt in to security with Multipeer Connectivity because you didn’t want to deal with PKI, consider the TLS-PSK options offered by Network framework. For more on this topic, see Plan for security.
When you advertise a service, the default behaviour is to use the user-assigned device name as the service name. To override that, create a service with a custom name:
let listener: NWListener = …
let name: String = …
listener.service = .init(name: name, type: "_example._tcp")
It’s not uncommon for folks to user the peer identifier as the service name.
There are good reasons to persist your peer identifier, but doing so isn’t great for privacy. Persisting the identifier allows for tracking of your service over time and between networks. Consider whether you need a persistent peer identifier at all. If you do, consider whether it makes sense to rotate it over time.
A persistent peer identifier is especially worrying if you use it as your service name or put it in your TXT record.
Configure your connections
Multipeer Connectivity’s symmetric architecture means that it uses a single type, MCSession, to manage the connections to all peers.
In Network framework, that role is fulfilled by two types:
NWListener to listen for incoming connections.
NWConnection to make outgoing connections.
Both types require you to supply an NWParameters value that specifies the network protocol and options to use. In addition, when creating an NWConnection you pass in an NWEndpoint to tell it the service to connect to. For example, here’s how to configure a very simple listener for TCP:
let parameters = NWParameters.tcp
let listener = try NWListener(using: parameters)
… continue setting up the listener …
And here’s how you might configure an outgoing TCP connection:
let parameters = NWParameters.tcp
let endpoint = NWEndpoint.hostPort(host: "example.com", port: 80)
let connection = NWConnection.init(to: endpoint, using: parameters)
… continue setting up the connection …
NWParameters has properties to control exactly what protocol to use and what options to use with those protocols.
To work with QUIC connections, use code like that shown in the quicParameters() example from the Security section earlier in this post.
To work with TCP connections, use the NWParameters.tcp property as shown above.
To enable TLS on your TCP connections, use code like that shown in the tlsOverTCPParameters() example from the Security section earlier in this post.
To work with WebSocket connections, insert it into the application protocols array:
let parameters = NWParameters.tcp
let ws = NWProtocolWebSocket.Options(.version13)
parameters.defaultProtocolStack.applicationProtocols.insert(ws, at: 0)
To enable TLS on your WebSocket connections, use code like that shown in the tlsOverTCPParameters() example to create your base parameters and then add the WebSocket application protocol to that.
To work with UDP connections, use the NWParameters.udp property:
let parameters = NWParameters.udp
To enable TLS on your UDP connections, use code like that shown in the dtlsOverUDPParameters() example from the Security section earlier in this post.
Enable peer-to-peer Wi-Fi
By default, Network framework doesn’t use peer-to-peer Wi-Fi. To enable that, set the includePeerToPeer property on the parameters used to create your listener and connection objects.
parameters.includePeerToPeer = true
IMPORTANT Enabling peer-to-peer Wi-Fi can impact the performance of the network. Only opt into it if it’s a significant benefit to your app.
If you enable peer-to-peer Wi-Fi, it’s critical to stop network operations as soon as you’re done with them. For example, if you’re browsing for services with peer-to-peer Wi-Fi enabled and the user picks a service, stop the browse operation immediately. Otherwise, the ongoing browse operation might affect the performance of your connection.
Manage a listener
In Network framework, use NWListener to listen for incoming connections:
let parameters: NWParameters = .tcp
… configure parameters …
let listener = try NWListener(using: parameters)
listener.service = … service details …
listener.serviceRegistrationUpdateHandler = … handle service registration changes …
listener.stateUpdateHandler = { newState in
… handle state changes …
}
listener.newConnectionHandler = { newConnection in
… handle the new connection …
}
listener.start(queue: .main)
For details on how to set up parameters, see Configure your connections. For details on how to set up up service and serviceRegistrationUpdateHandler, see Discover peers.
Network framework calls your state update handler when the listener changes state:
let listener: NWListener = …
listener.stateUpdateHandler = { newState in
switch newState {
case .setup:
// The listener has not yet started.
…
case .waiting(let error):
// The listener tried to start and failed. It might recover in the
// future.
…
case .ready:
// The listener is running.
…
case .failed(let error):
// The listener tried to start and failed irrecoverably.
…
case .cancelled:
// The listener was cancelled by you.
…
@unknown default:
break
}
}
Network framework calls your new connection handler when a client connects to it:
var connections: [NWConnection] = []
let listener: NWListener = listener
listener.newConnectionHandler = { newConnection in
… configure the new connection …
newConnection.start(queue: .main)
connections.append(newConnection)
}
IMPORTANT Don’t forget to call start(queue:) on your connections.
In Multipeer Connectivity, the session (MCSession) keeps track of all the peers you’re communicating with. With Network framework, that responsibility falls on you. This example uses a simple connections array for that purpose. In your app you may or may not need a more complex data structure. For example:
In the client/server network architecture, the client only needs to manage the connections to a single peer, the server.
On the other hand, the server must managed the connections to all client peers.
In the star network architecture, every peer must maintain a listener and connections to each of the other peers.
Understand UDP flows
Network framework handles UDP using the same NWListener and NWConnection types as it uses for TCP. However, the underlying UDP protocol is not implemented in terms of listeners and connections. To resolve this, Network framework works in terms of UDP flows. A UDP flow is defined as a bidirectional sequence of UDP datagrams with the same 4 tuple (local IP address, local port, remote IP address, and remote port). In Network framework:
Each NWConnection object manages a single UDP flow.
If an NWListener receives a UDP datagram whose 4 tuple doesn’t match any known NWConnection, it creates a new NWConnection.
Manage a connection
In Network framework, use NWConnection to start an outgoing connection:
var connections: [NWConnection] = []
let parameters: NWParameters = …
let endpoint: NWEndpoint = …
let connection = NWConnection(to: endpoint, using: parameters)
connection.stateUpdateHandler = … handle state changes …
connection.viabilityUpdateHandler = … handle viability changes …
connection.pathUpdateHandler = … handle path changes …
connection.betterPathUpdateHandler = … handle better path notifications …
connection.start(queue: .main)
connections.append(connection)
As in the listener case, you’re responsible for keeping track of this connection.
Each connection supports four different handlers. Of these, the state and viability update handlers are the most important. For information about the path update and better path handlers, see the NWConnection documentation.
Network framework calls your state update handler when the connection changes state:
let connection: NWConnection = …
connection.stateUpdateHandler = { newState in
switch newState {
case .setup:
// The connection has not yet started.
…
case .preparing:
// The connection is starting.
…
case .waiting(let error):
// The connection tried to start and failed. It might recover in the
// future.
…
case .ready:
// The connection is running.
…
case .failed(let error):
// The connection tried to start and failed irrecoverably.
…
case .cancelled:
// The connection was cancelled by you.
…
@unknown default:
break
}
}
If you a connection is in the .waiting(_:) state and you want to force an immediate retry, call the restart() method.
Network framework calls your viability update handler when its viability changes:
let connection: NWConnection = …
connection.viabilityUpdateHandler = { isViable in
… react to viability changes …
}
A connection becomes inviable when a network resource that it depends on is unavailable. A good example of this is the network interface that the connection is running over. If you have a connection running over Wi-Fi, and the user turns off Wi-Fi or moves out of range of their Wi-Fi network, any connection running over Wi-Fi becomes inviable.
The inviable state is not necessarily permanent. To continue the above example, the user might re-enable Wi-Fi or move back into range of their Wi-Fi network. If the connection becomes viable again, Network framework calls your viability update handler with a true value.
It’s a good idea to debounce the viability handler. If the connection becomes inviable, don’t close it down immediately. Rather, wait for a short while to see if it becomes viable again.
If a connection has been inviable for a while, you get to choose as to how to respond. For example, you might close the connection down or inform the user.
To close a connection, call the cancel() method. This gracefully disconnects the underlying network connection. To close a connection immediately, call the forceCancel() method. This is not something you should do as a matter of course, but it does make sense in exceptional circumstances. For example, if you’ve determined that the remote peer has gone deaf, it makes sense to cancel it in this way.
Send and receive reliable messages
In Multipeer Connectivity, a single session supports both reliable and best effort send modes. In Network framework, a connection is either reliable or best effort, depending on the underlying network protocol.
The exact mechanism for sending a message depends on the underlying network protocol. A good protocol for reliable messages is WebSocket. To send a message on a WebSocket connection:
let connection: NWConnection = …
let message: Data = …
let metadata = NWProtocolWebSocket.Metadata(opcode: .binary)
let context = NWConnection.ContentContext(identifier: "send", metadata: [metadata])
connection.send(content: message, contentContext: context, completion: .contentProcessed({ error in
// … check `error` …
_ = error
}))
In WebSocket, the content identifier is ignored. Using an arbitrary fixed value, like the send in this example, is just fine.
Multipeer Connectivity allows you to send a message to multiple peers in a single send call. In Network framework each send call targets a specific connection. To send a message to multiple peers, make a send call on the connection associated with each peer.
If your app needs to transfer arbitrary amounts of data on a connection, it must implement flow control. See Start a stream, below.
To receive messages on a WebSocket connection:
func startWebSocketReceive(on connection: NWConnection) {
connection.receiveMessage { message, _, _, error in
if let error {
… handle the error …
return
}
if let message {
… handle the incoming message …
}
startWebSocketReceive(on: connection)
}
}
IMPORTANT WebSocket preserves message boundaries, which is one of the reasons why it’s ideal for your reliable messaging connections. If you use a streaming protocol, like TCP or QUIC streams, you must do your own framing. A good way to do that is with NWProtocolFramer.
If you need the metadata associated with the message, get it from the context parameter:
connection.receiveMessage { message, context, _, error in
…
if let message,
let metadata = context?.protocolMetadata(definition: NWProtocolWebSocket.definition) as? NWProtocolWebSocket.Metadata
{
… handle the incoming message and its metadata …
}
…
}
Send and receive best effort messages
In Multipeer Connectivity, a single session supports both reliable and best effort send modes. In Network framework, a connection is either reliable or best effort, depending on the underlying network protocol.
The exact mechanism for sending a message depends on the underlying network protocol. A good protocol for best effort messages is UDP. To send a message on a UDP connection:
let connection: NWConnection = …
let message: Data = …
connection.send(content: message, completion: .idempotent)
IMPORTANT UDP datagrams have a theoretical maximum size of just under 64 KiB. However, sending a large datagram results in IP fragmentation, which is very inefficient. For this reason, Network framework prevents you from sending UDP datagrams that will be fragmented. To find the maximum supported datagram size for a connection, gets its maximumDatagramSize property.
To receive messages on a UDP connection:
func startUDPReceive(on connection: NWConnection) {
connection.receiveMessage { message, _, _, error in
if let error {
… handle the error …
return
}
if let message {
… handle the incoming message …
}
startUDPReceive(on: connection)
}
}
This is exactly the same code as you’d use for WebSocket.
Start a stream
In Multipeer Connectivity, you can ask the session to start a stream to a specific peer. There are two ways to achieve this in Network framework:
If you’re using QUIC for your reliable connection, start a new QUIC stream over that connection. This is one place that QUIC shines. You can run an arbitrary number of QUIC connections over a single QUIC connection group, and QUIC manages flow control (see below) for each connection and for the group as a whole.
If you’re using some other protocol for your reliable connection, like WebSocket, you must start a new connection. You might use TCP for this new connection, but it’s not unreasonable to use WebSocket or QUIC.
If you need to open a new connection for your stream, you can manage that process over your reliable connection. Choose a protocol to match your send mode explains the general approach for this, although in that case it’s opening a parallel best effort UDP connection rather than a parallel stream connection.
The main reason to start a new stream is that you want to send a lot of data to the remote peer. In that case you need to worry about flow control. Flow control applies to both the send and receive side.
IMPORTANT Failing to implement flow control can result in unbounded memory growth in your app. This is particularly bad on iOS, where jetsam will terminate your app if it uses too much memory.
On the send side, implement flow control by waiting for the connection to call your completion handler before generating and sending more data. For example, on a TCP connection or QUIC stream you might have code like this:
func sendNextChunk(on connection: NWConnection) {
let chunk: Data = … read next chunk from disk …
connection.send(content: chunk, completion: .contentProcessed({ error in
if let error {
… handle error …
return
}
sendNextChunk(on: connection)
}))
}
This acts like an asynchronous loop. The first send call completes immediately because the connection just copies the data to its send buffer. In response, your app generates more data. This continues until the connection’s send buffer fills up, at which point it defers calling your completion handler. Eventually, the connection moves enough data across the network to free up space in its send buffer, and calls your completion handler. Your app generates another chunk of data
For best performance, use a chunk size of at least 64 KiB. If you’re expecting to run on a fast device with a fast network, a chunk size of 1 MiB is reasonable.
Receive-side flow control is a natural extension of the standard receive pattern. For example, on a TCP connection or QUIC stream you might have code like this:
func receiveNextChunk(on connection: NWConnection) {
let chunkSize = 64 * 1024
connection.receive(minimumIncompleteLength: chunkSize, maximumLength: chunkSize) { chunk, _, isComplete, error in
if let chunk {
… write chunk to disk …
}
if isComplete {
… close the file …
return
}
if let error {
… handle the error …
return
}
receiveNextChunk(on: connection)
}
}
IMPORTANT The above is cast in terms of writing the chunk to disk. That’s important, because it prevents unbounded memory growth. If, for example, you accumulated the chunks into an in-memory buffer, that buffer could grow without bound, which risks jetsam terminating your app.
The above assumes that you can read and write chunks of data synchronously and promptly, for example, reading and writing a file on a local disk. That’s not always the case. For example, you might be writing data to an accessory over a slow interface, like Bluetooth LE. In such cases you need to read and write each chunk asynchronously.
This results in a structure where you read from an asynchronous input and write to an asynchronous output. For an example of how you might approach this, albeit in a very different context, see Handling Flow Copying.
Send a resource
In Multipeer Connectivity, you can ask the session to send a complete resource, identified by either a file or HTTP URL, to a specific peer. Network framework has no equivalent support for this, but you can implement it on top of a stream:
To send, open a stream and then read chunks of data using URLSession and send them over that stream.
To receive, open a stream and then receive chunks of data from that stream and write those chunks to disk.
In this situation it’s critical to implement flow control, as described in the previous section.
Final notes
This section collects together some general hints and tips.
Concurrency
In Multipeer Connectivity, each MCSession has its own internal queue and calls delegate callbacks on that queue. In Network framework, you get to control the queue used by each object for its callbacks. A good pattern is to have a single serial queue for all networking, including your listener and all connections.
In a simple app it’s reasonable to use the main queue for networking. If you do this, be careful not to do CPU intensive work in your networking callbacks. For example, if you receive a message that holds JPEG data, don’t decode that data on the main queue.
Overriding protocol defaults
Many network protocols, most notably TCP and QUIC, are intended to be deployed at vast scale across the wider Internet. For that reason they use default options that aren’t optimised for local networking. Consider changing these defaults in your app.
TCP has the concept of a send timeout. If you send data on a TCP connection and TCP is unable to successfully transfer it to the remote peer within the send timeout, TCP will fail the connection.
The default send timeout is infinite. TCP just keeps trying. To change this, set the connectionDropTime property.
TCP has the concept of keepalives. If a connection is idle, TCP will send traffic on the connection for two reasons:
If the connection is running through a NAT, the keepalives prevent the NAT mapping from timing out.
If the remote peer is inaccessible, the keepalives fail, which in turn causes the connection to fail. This prevents idle but dead connections from lingering indefinitely.
TCP keepalives default to disabled. To enable and configure them, set the enableKeepalive property. To configure their behaviour, set the keepaliveIdle, keepaliveCount, and keepaliveInterval properties.
Symbol cross reference
If you’re not sure where to start with a specific Multipeer Connectivity construct, find it in the tables below and follow the link to the relevant section.
[Sorry for the poor formatting here. DevForums doesn’t support tables properly, so I’ve included the tables as preformatted text.]
| For symbol | See |
| ----------------------------------- | --------------------------- |
| `MCAdvertiserAssistant` | *Discover peers* |
| `MCAdvertiserAssistantDelegate` | *Discover peers* |
| `MCBrowserViewController` | *Discover peers* |
| `MCBrowserViewControllerDelegate` | *Discover peers* |
| `MCNearbyServiceAdvertiser` | *Discover peers* |
| `MCNearbyServiceAdvertiserDelegate` | *Discover peers* |
| `MCNearbyServiceBrowser` | *Discover peers* |
| `MCNearbyServiceBrowserDelegate` | *Discover peers* |
| `MCPeerID` | *Create a peer identifier* |
| `MCSession` | See below. |
| `MCSessionDelegate` | See below. |
Within MCSession:
| For symbol | See |
| --------------------------------------------------------- | ------------------------------------ |
| `cancelConnectPeer(_:)` | *Manage a connection* |
| `connectedPeers` | *Manage a listener* |
| `connectPeer(_:withNearbyConnectionData:)` | *Manage a connection* |
| `disconnect()` | *Manage a connection* |
| `encryptionPreference` | *Plan for security* |
| `myPeerID` | *Create a peer identifier* |
| `nearbyConnectionData(forPeer:withCompletionHandler:)` | *Discover peers* |
| `securityIdentity` | *Plan for security* |
| `send(_:toPeers:with:)` | *Send and receive reliable messages* |
| `sendResource(at:withName:toPeer:withCompletionHandler:)` | *Send a resource* |
| `startStream(withName:toPeer:)` | *Start a stream* |
Within MCSessionDelegate:
| For symbol | See |
| ---------------------------------------------------------------------- | ------------------------------------ |
| `session(_:didFinishReceivingResourceWithName:fromPeer:at:withError:)` | *Send a resource* |
| `session(_:didReceive:fromPeer:)` | *Send and receive reliable messages* |
| `session(_:didReceive:withName:fromPeer:)` | *Start a stream* |
| `session(_:didReceiveCertificate:fromPeer:certificateHandler:)` | *Plan for security* |
| `session(_:didStartReceivingResourceWithName:fromPeer:with:)` | *Send a resource* |
| `session(_:peer:didChange:)` | *Manage a connection* |
Revision History
2025-03-11 Expanded the Enable peer-to-peer Wi-Fi section to stress the importance of stopping network operations once you’re done with them. Added a link to that section from the list of Multipeer Connectivity drawbacks.
2025-03-07 First posted.
I use eapolcfg in Apple's open source eap8021x repository to connect to the enterprise network.
1.https://github.com/gfleury/eap8021x-debug
https://opensource.apple.com/source/eap8021x/eap8021x-304.100.1/
Our enterprise network authentication is PEAP. So far, I have created a profile using the following commands and have done the access.
./eapolcfg createProfile --authType PEAP --SSID myssid --securityType WPA2 --userDefinedName MyProfile
./eapolcfg setPasswordItem --password mypassword --name myname --SSID myssid
./eapolcfg startAuthentication --interface en0 --SSID myssid
After I performed this series of operations, I passed
BOOL success = [self.interface associateToEnterpriseNetwork:network identity:nil username:username password:password error:&error];
Connection will pop up the following pop-up window, sometimes associateToEnterpriseNetwork will fail. I don't know what went wrong, is it that I missed some steps through the eapolcfg [tool?]
This function also reports the following error:Error Domain=com.apple.coreWLAN.EAPOL.error Code=1
"(null)"
Please answer my questions. Thank you very much
Our app receives real-time GPS and aircraft data from devices via UDP broadcast and/or multicast on a WiFi network created by the device.
We have identified that the iPhone or iPad will just stop receiving UDP broadcast/multicast data for an interval of time. In general, it appears after roughly every 128KB of data is received.
In the attached screenshot from Xcode instruments, you can see the data reception alternating on/off.
We have verified with Wireshark that the data is still flowing during that entire time period. And by tracking bytes received the app ultimately receives about 55% of the bytes, which tracks with the Network graph.
We have used different approaches to the network code, including GCDAsyncUdpSocket, BSD Sockets, and the Network framework. We've tried it on background threads and the main thread. Tested it on iPads and iPhones. All produce the same result. The data is just never reaching the app code.
Any insight on what may be temporarily disabling data reception?
I'm using Network Framework to transfer files between 2 devices. The "secondary" device sends file requests to the "primary" device, and the primary sends the files back.
When the primary gets the request, it responds like this:
do {
let data = try Data(contentsOf: filePath)
let priSecDataFilePacket = PriSecDataFilePacket(fileName: filename, dataBlob: data)
let jsonData = try JSONEncoder().encode(priSecDataFilePacket)
let message = NWProtocolFramer.Message(priSecMessageType: PriSecMessageType.priToSecDataFile)
let context = NWConnection.ContentContext(identifier: "TransferUtility", metadata: [message])
connection.send(content: encodedJsonToSend, contentContext: context, isComplete: true, completion: .idempotent)
} catch {
print("\(error)")
}
It works great, even for hundreds of file requests. The problem arises if some files being requested are extremely large, like 600MB. You can see the memory speedometer on the primary quickly ramp up to the yellow zone, at which point iOS kills the app for high memory use, and you see the Jetsam log.
I changed the code to skip JSON encoding the binary file as a test, and that helped a bit, but it still goes too high; the real offender is the step where it loads the 600MB file into the data var:
let data = try Data(contentsOf: filePath)
If I remark out everything else and just leave that one line, I can still see the memory use spike.
As a fix, I'm rewriting this so the secondary requests the file in 5MB chunks by telling the primary a byte range such as "0-5242880" or "5242881-10485760", and then reassembling the chunks on the secondary once they all come in. So far this seems promising, but it's a fair amount of work.
My question: Does Network Framework have a built-in way to stream those bytes straight from disk as it sends them? So that I could send all the data in one single request without having to load the bytes into memory?
HI,
I am currently prototyping an app that compares transport protocol performances using a peer to peer connection. I have already setup TCP and UDP connections and am sending data between the clients, it works like I want it to.
Next I was trying to setup a connection using QUIC, but the NWConnection.State stays in the preparing state and I couldn't find a way to get more information from the framework or the instances about why it was not fully connecting. After searching the internet and stumbling across the forum I noticed that the missing encryption might be the issue, so I created a local root certificate*. Then I used the SecPKCS12Import function to read/extract the SecIdentity instance of the p12 file (cert + private key) stored in my bundle** and set it as a local identity with the sec_protocol_options_set_local_identity function***.
//function that creates/returns different NWParameteres
//...
let quicOptions = NWProtocolQUIC.Options()
quicOptions.alpn = ["test"]
if let identityPath = Bundle.main.path(forResource: "QUICConnect", ofType: "p12"),
let identityData = try? Data(contentsOf: URL(fileURLWithPath: identityPath)) {
if let identity = loadIdentityFromPKCS12(p12Path: identityPath, password: "insecure") { //****
sec_protocol_options_set_local_identity(quicOptions.securityProtocolOptions, sec_identity_create(identity)!)
}
}
let parameters = NWParameters(quic: quicOptions)
parameters.includePeerToPeer = true
return parameter
The documentation comments had me thinking that setting a local identity could be enough, since it consists of the private key for the "server" and the cert for the "client".
Set the local identity to be used for this protocol instance.
Unfortunately at this stage the QUIC Connection is still stuck in preparing state and since I don't know how to extract more information from the networking connection instances/framework, I am stuck.
I have seen the following other functions in Quinns answer and am confident that I could somehow figure it out with some more time put into it, but not really understanding why or how I could do it better in the future. So I am also wondering how I could have found info about this more efficiently and tackled this more strategically without needing to browse through so many forums.
sec_protocol_options_set_verify_block
sec_protocol_options_set_challenge_block
I would really appreciate any help, many thanks.
BR Matthias!
TLDR:
I want to establish a peer to peer QUIC Connection but the state is stuck in preparing. Secondary question is how I could approach a similar topic more efficiently next time, instead of browsing many forums.
* I had to create it with the openssl CLI since the keychain app created a cert, that when using the openssl CLI to get the info would throw an error unless used with the -legacy flag. The root cert, created form the keychain app also wasn't able to be imported by the SecPKCS12Import function. No clue why but it worked with a cert created from the openssl CLI. There's a chance that I messed up something else here, but these were my experiences. Info: Since QUIC is limited to TLS v1.3 I can't use PSK, afaik. Therefore the TicTacToe doesn't help me anymore.
** I know this is highly insecure, I am just using it for prototyping.
*** Forum users Info: One needs to use the sec_identity_create function to convert the SecIdentity instance to the expected parameter type.
****
func loadIdentityFromPKCS12(p12Path: String, password: String) -> SecIdentity? {
guard let p12Data = try? Data(contentsOf: URL(fileURLWithPath: p12Path)) else {
print("didnt find p12 file at path")
return nil
}
let options: NSDictionary = [kSecImportExportPassphrase as String: password, kSecImportToMemoryOnly as String: kCFBooleanTrue!]
var items: CFArray?
let status = SecPKCS12Import(p12Data as CFData, options, &items)
if status == 0, let dict = (items as? [[String: Any]])?.first {
if let identity = dict[kSecImportItemIdentity as String] {
return identity as! SecIdentity
} else {
return nil
}
} else {
return nil
}
}
PS: For TCP and UDP I am using bonjour to discover the peer and connect to the advertised ports. AFAIK I can't just use _testproto._quic to advertise a QUIC service like with tcp and udp. Therefore I am using the local domain name (it's just for prototyping and always the same device) and a hard coded port number to create the peer connection. When using a wrong name the DNS threw an error telling it could not find a peer, so the lookup itself is working I guess. The lookup should come from the cache since I already looked up when connecting to the same peer via Bonjour.
//Server
//....
listener = try NWListener(
using: transportProtocol.parameters,
on: Config.quicPort
)
//...
listener.newConnectionHandler = { [weak self] connection in
self?.connection?.cancel()
self?.connection = nil
self?.connection = C(connection) //here C is a generic that conforms to a custom connection interface, nothing to worry about :)
self?.connectionStatus.value = "Connection established"
}
listener.stateUpdateHandler = { [weak self] state in
self?.connectionStatus.value = "\(state)"
}
listener.start(queue: .global())
//Client
//...
nwConnection = NWConnection(host: "iPad.local.", port: Config.quicPort, using: transportProtocol.parameters)
//...
I'm working on two Swift applications which are using QUIC in Network.framework for communication, one serve as the listener (server) and the other serve as the client so that they can exchange data, both the server and the client app are running under the same LAN, the problem I met is that when client try to connect to the server, the connection will fail due to boring SSL, couple questions:
Since both the server app and client app are running under the same LAN, do they need TLS certificate?
If it does, will self-signed certificate P12 work? I might distribute the app in App Store or in signed/notarized dmg or pkg to our users.
If I need a public certificate and self signed wouldn't work, since they are just pair of apps w/o fixed dns domain etc, Is there any public certificate only for standalone application, not for the fixed web domain?
I am looking for inputs to better understand MacOS entitlements. I ask this in context of OpenJDK project, which builds and ships the JDK. The build process makes uses of make tool and thus doesn't involving building through the XCode product. The JDK itself is a Java language platform providing applications a set of standard APIs. The implementation of these standard APIs internally involves calling platform specific native library functions. In this discussion, I would like to focus on the networking functions that the implementation uses. Almost all of these networking functions and syscalls that the internal implementation uses are BSD socket related. Imagine calls to socket(), connect(), getsockopt(), setsockopt(), getaddrinfo(), sendto(), listen(), accept() and several such.
The JDK that's built through make is then packaged and made available for installation. The packaging itself varies, but for this discussion, I'll focus on the .tar.gz archived packaging. Within this archive there are several executables (for example: java, javac and others) and several libraries. My understanding, based on what I have read of MacOS entitlements is that, the entitlements are set on the executable and any libraries that would be loaded and used by that executable will be evaluated against the entitlements of the executable (please correct me if I misunderstand).
Reading through the list of entitlements noted here https://developer.apple.com/documentation/bundleresources/entitlements, the relevant entitlements that an executable (like "java") which internally invokes BSD socket related syscalls and library functions, appear to be:
com.apple.security.network.client - https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.security.network.client
com.apple.security.network.server - https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.security.network.server
com.apple.developer.networking.multicast - https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.developer.networking.multicast
Is my understanding correct that these are the relevant ones for MacOS? Are there any more entitlements that are of interest? Would it then mean that the executables (java for example) would have to enroll for these entitlements to be allowed to invoke those functions at runtime?
Reading through https://developer.apple.com/documentation/bundleresources/entitlements, I believe that even when an executable is configured with these entitlements, when the application is running if that executable makes use of any operations for which it has an entitlement, the user is still prompted (through a UI notification) whether or not to allow the operation. Did I understand it right?
The part that isn't clear from that documentation is, if the executable hasn't been configured with a relevant entitlement, what happens when the executable invokes on such operation. Will the user see a UI notification asking permission to allow the operation (just like if an entitlement was configured)? Or does that operation just fail in some behind the scenes way?
Coming back to the networking specific entitlements, I found a couple of places in the MacOS documentation where it is claimed that the com.apple.developer.networking.multicast entitlement is only applicable on iOS. In fact, the entitlement definition page for it https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.developer.networking.multicast says:
"Your app must have this entitlement to send or receive IP multicast or broadcast on iOS. It also allows your app to browse and advertise arbitrary Bonjour service types."
Yet, that same page, a few lines above, shows "macOS 10.0+". So, is com.apple.developer.networking.multicast entitlement necessary for an executable running on MacOS which deals with multicasting using BSD sockets?
As a more general comment about the documentation, I see that the main entitlements page here https://developer.apple.com/documentation/bundleresources/entitlements categorizes some of these entitlements under specific categories, for example, notice how some entitlements are categorized under "App Clips". I think it would be useful if there was a category for "BSD sockets" and under that it would list all relevant entitlements that are applicable, even if it means repeating the entitlement names across different categories. I think that will make it easier to identify the relevant entitlements.
Finally, more as a long term question, how does one watch or keep track of these required entitlements for these operations. What I mean is, is it expected that application developers keep visiting the macos documentation, like these pages, to know that a new entitlement is now required in a new macos (update) release? Or are there other ways to keep track of it? For example, if a newer macos requires a new entitlement, then when (an already built) executable is run on that version of macos, perhaps generate a notification or some kind of explicit error which makes it clear what entitlement is missing? I have read through https://developer.apple.com/documentation/bundleresources/diagnosing-issues-with-entitlements but that page focuses on identifying such issues when a executable is being built and doesn't explain the case where an executable has already been shipped with X entitlements and a new Y entitlement is now required to run on a newer version of macos.
I have an iPhone app which relies heavily on TCP/IP communication in the local network. Therefore, the application starts a server socket and accepts incoming connections. This worked flawlessly for a long time and we had no problems with this.
Problem
In the last days however, we observed that for some iPhones with the server role other devices cannot connect to the server of our app. The server does not accept incoming connections on the devices IP address and the client times out.
Environment
Both iPhones (the server and the client) are in the same network with 192.168.1.0 address range and 255.255.255.0 subnet mask. The server has the IP 192.168.1.11 and the client has 192.168.1.22. This is a normal home WiFi network with no special firewall rules. Both devices have mobile data disabled and the "access local network" permission is granted. The server socket is bound to all interfaces (0.0.0.0).
More technical symptoms
When the server iPhone is in this faulty state, it seems like it somehow has two ip addresses:
192.168.2.123 and 192.168.1.11
The WiFi preferences show the (correct) .1.11 ip address. The Apps however see the (wrong) .2.123 ip address. I cannot explain where the other ip address comes from and why the device thinks it has this ip address.
I've collected interface diagnosis information on a faulty iPhone and it listed the following interfaces and IPs:
en0 -> 192.168.2.123
lo0 -> 127.0.0.1
pdp_ip0 (cellular) -> 192.0.0.2
pdp_ip1 to pdp_ip6 (cellular) -> -/-
ipsec0 to ipsec6 (vpn) -> -/-
llw0 (vpn) -> -/-
awdl0 -> -/-
anpi0 -> -/-
ap1 -> -/-
XHC0 -> -/-
en1 and en2 (wired) -> -/-
utun0 to utun2 (vpn) -> -/-
The correct ip of the device is not listed anywhere in this list.
A reboot helped to temporarily fix this problem. One user reported the same issue again a few hours later after a reboot. Switching off WiFi and reconnecting does not solve the problem.
This issue occurred on several iPhones with the following specs:
iOS Version 18.1.1, 18.3.1
iPhone 13 Pro, iPhone 13 Pro Max, iPhone 15 Pro
The problem must be on the server side as the client can successfully connect to any other device in the same network.
Question(s)
Where does this second IP come from and why does the server not accept connections to either ip even though it is bound to 0.0.0.0?
Are there any iOS system settings which could lead to this problem? (privacy setting, vpn, ...)
What could be done to permanently fix this issue?
We have developed a DNS filter extension that works for most applications, but it does not receive all DNS queries.
In particular, if we have our extension installed and enabled, we see Safari browsing cause local DNS servers to be used instead of going through our extension.
What is the logic for how DNS servers vs. extensions are chosen to resolve DNS queries?
Here's a simple program that spoofs an ARP reply for a given IP address. If I spin up two terminal sessions on the same machine.
Run this code in one window
% ./spoof en0 192.168.1.7
Listening on en0 for ARP requests to 192.168.1.7
Spoofing MAC: 00:0c:87:47:50:27
And in the second window cause the OS to issue an ARP_REQ
% ping 192.168.1.7
You will see the program respond to the ARP request. (Wireshark will see the ARP_REQ and ARP_REPLY packets) however my arp table isn't updated with the MAC for the IP address. There is no firewall active.
% arp -a|grep 192.168.1.7
(192.168.1.7) at (incomplete) on en0 ifscope [ethernet]
This is running on a MacBook pro M3 (OSX 15.4).
HOWEVER, on a MacBook pro M4 (OSX 15.2) is does Work !!!!!
Can anyone explain why its not working?
spoof.txt
Dear Apple Developer Support,
I hope this message finds you well. I am reaching out for guidance on a project that involves sharing heart rate data between an iOS app and an Android app. I have developed a watchOS app that continuously fetches heart rate data from an Apple Watch and displays it in a companion iOS app. Additionally, I have built an Android fitness app using Ionic Angular.
My goal is to create a bridge that allows the heart rate data from the iOS app to be displayed continuously in the Android app. I am considering using a backend server (e.g., Node.js) to facilitate this data transfer.
Could you please provide any insights or recommendations on the best approach for achieving this cross-platform data sharing? I would appreciate any guidance on potential challenges or limitations I might encounter.
Thank you for your time and assistance.
Sincerely,
Venu Madhav
Hi, I've noticed a weird behavior happening on Sequoia with DF bit:
On machine where SIP is disabled, when I do /sbin/ping -D -s 1400 8.8.8.8 I do see the DF bit in wireshark
On machine where SIP is enabled, when I do /sbin/ping -D -s 1400 8.8.8.8 I do not see the DF bit in wireshark
The -D flag should set the DF bit but for some reason it doesn’t if the SIP is enabled.
Perhaps there was any change in permission/entitlements mechanism in Sequoia that can explain it ? I'm using the built-in ping command so maybe it should be signed with more entitlements ?
Swift recently added support for Int128. However, they do need NOT seem to be supported in SwiftData. Now totally possible I'm doing something wrong too.
I have the project set to macOS 15 to use a UInt128 in @Model class as attribute. I tried using a clean Xcode project with Swift Data choosen in the macOS app wizard.
Everything compiles, but it fails at runtime in both my app and "Xcode default" SwiftData:
SwiftData/SchemaProperty.swift:380: Fatal error: Unexpected property within Persisted Struct/Enum: Builtin.Int128
with the only modification to from stock is:
@Model
final class Item {
var timestamp: Date
var ipv6: UInt128
init(timestamp: Date) {
self.timestamp = timestamp
self.ipv6 = 0
}
}
I have tried both Int128 and UInt128. Both fails exactly the same. In fact, so exactly, when using UInt128 it still show a "Int128" in error message, despite class member being UInt128 .
My underlying need is to store an IPv6 addresses with an app, so the newer UInt128 would work to persist it. Since Network Framework IPv6Address is also not compatible, it seems, with SwiftData. So not a lot of good options, other an a String. But for an IPv6 address that suffers from that same address can take a few String forms (i.e. "0000:0000:0000:0000:0000:0000:0000:0000" =="0:0:0:0:0:0:0:0" == "::") which is more annoying than having a few expand Int128 as String separator ":".
Ideas welcomed. But potentially a bug in SwiftData since Int128 is both a Builtin and conforms to Codable, so from my reading it should work.
Hello Apple Developer Team,
Based on the mandate to update the APNs certificate by February 24, 2025 for certificate-based authentication, a question from the team has been brought up that maybe Apple or the community can help answer. Since our implementation uses token-based authentication, I’m seeking clarification on a couple of points:
1. Does the certificate update affect token-based connections at all?
2. What is the rationale behind updating certificates for certificate-based authentication, and are there any implications or benefits for developers using token-based authentication?
Understanding these details will help us ensure our system remains compliant and optimally configured. Any guidance or further clarification you can provide would be greatly appreciated.
Thank you!
Hi Everyone,
I’m working on a communication system for my app using NWConnection with the UDP protocol. The connection is registered to a custom serial dispatch queue. However, I’m trying to understand what the behavior will be in a scenario where the connection is canceled while there are still pending receive operations in progress.
Scenario Overview:
The sender is transmitting n = 100 packets to the receiver, out of which 40 packets have already been sent (i.e., delivered to the Receiver).
The receiver has posted m = 20 pending receive operations, where each receive operation is responsible for handling one packet.
The receiver has already successfully processed x = 10 packets.
At the time of cancellation, the receiver’s buffer still holds m = 20 packets that are pending for processing, and k = 10 pending receive callbacks are in the dispatch queue, waiting to be executed.
At same time when the 10th packet was processed another thread triggers .cancel() on this accepted NWConnection (on the receiver side), I need to understand the impact on the pending receive operations and their associated callbacks.
My Questions:
What happens to the k = 10 pending receive callbacks that are in the dispatch queue waiting to be triggered when the connection is canceled? Will these callbacks complete successfully and process the data? Or, because the connection is canceled, will they complete with failure?
What happens to the remaining pending receive operations that were initiated but have not yet been scheduled in the dispatch queue? For the pending receive operations that were already initiated (i.e., the network stack is waiting to receive the data, but the callback hasn’t been scheduled yet), will they fail immediately when the connection is canceled? Or is there any chance that the framework might still process these receives before the cancellation fully takes effect?