General:
Forums subtopic: App & System Services > Networking
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 forums 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
TN3179 Understanding local network privacy
Adapt to changing network conditions tech talk
Understanding Also-Ran Connections forums post
Extra-ordinary Networking forums post
Foundation networking:
Forums tags: Foundation, CFNetwork
URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms.
Network framework:
Forums tag: Network
Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms.
Building a custom peer-to-peer protocol sample code (aka TicTacToe)
Implementing netcat with Network Framework sample code (aka nwcat)
Configuring a Wi-Fi accessory to join a network sample code
Moving from Multipeer Connectivity to Network Framework forums post
Network Extension (including Wi-Fi on iOS):
See Network Extension Resources
Wi-Fi Fundamentals
TN3111 iOS Wi-Fi API overview
Wi-Fi Aware framework documentation
Wi-Fi on macOS:
Forums tag: Core WLAN
Core WLAN framework documentation
Wi-Fi Fundamentals
Secure networking:
Forums 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
What’s new for enterprise in iOS 18 support article — This discusses new key usage requirements.
Technote 2232 HTTPS Server Trust Evaluation
Technote 2326 Creating Certificates for TLS Testing
QA1948 HTTPS and Test Servers
Miscellaneous:
More network-related forums tags: 5G, QUIC, Bonjour
On FTP forums post
Using the Multicast Networking Additional Capability forums post
Investigating Network Latency Problems forums post
WirelessInsights framework documentation
iOS Network Signal Strength
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Networking
RSS for tagExplore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm using NERelayManager to set Relay configuration which all works perfectly fine.
I then do a curl with the included domain and while I see QUIC connection succeeds with relay server and H3 request goes to the server, the connection gets abruptly closed by the client with "Software caused connection abort".
Console has this information:
default 09:43:04.459517-0700 curl nw_flow_connected [C1.1.1 192.168.4.197:4433 in_progress socket-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], ipv4, ipv6, dns, uses wifi)] Transport protocol connected (quic)
default 09:43:04.459901-0700 curl [C1.1.1 192.168.4.197:4433 in_progress socket-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], ipv4, ipv6, dns, uses wifi)] event: flow:finish_transport @0.131s
default 09:43:04.460745-0700 curl nw_flow_connected [C1.1.1 192.168.4.197:4433 in_progress socket-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], ipv4, ipv6, dns, uses wifi)] Joined protocol connected (http3)
default 09:43:04.461049-0700 curl [C1.1.1 192.168.4.197:4433 in_progress socket-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], ipv4, ipv6, dns, uses wifi)] event: flow:finish_transport @0.133s
default 09:43:04.465115-0700 curl [C2 E47A3A0C-7275-4F6B-AEDF-59077ABAE34B 192.168.4.197:4433 quic, multipath service: 1, tls, definite, attribution: developer] cancel
default 09:43:04.465238-0700 curl [C2 E47A3A0C-7275-4F6B-AEDF-59077ABAE34B 192.168.4.197:4433 quic, multipath service: 1, tls, definite, attribution: developer] cancelled
[C2 FCB1CFD1-4BF9-4E37-810E-81265D141087 192.168.4.139:53898<->192.168.4.197:4433]
Connected Path: satisfied (Path is satisfied), viable, interface: en0[802.11], ipv4, ipv6, dns, uses wifi
Duration: 0.121s, QUIC @0.000s took 0.000s, TLS 1.3 took 0.111s
bytes in/out: 2880/4322, packets in/out: 4/8, rtt: 0.074s, retransmitted bytes: 0, out-of-order bytes: 0
ecn packets sent/acked/marked/lost: 3/1/0/0
default 09:43:04.465975-0700 curl nw_flow_disconnected [C2 192.168.4.197:4433 cancelled multipath-socket-flow ((null))] Output protocol disconnected
default 09:43:04.469189-0700 curl nw_endpoint_proxy_receive_report [C1.1 IPv4#124bdc4d:80 in_progress proxy (satisfied (Path is satisfied), interface: en0[802.11], ipv4, ipv6, dns, proxy, uses wifi)] Privacy proxy failed with error 53 ([C1.1.1] masque Proxy: http://192.168.4.197:4433)
default 09:43:04.469289-0700 curl [C1.1.1 192.168.4.197:4433 failed socket-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], ipv4, ipv6, dns, uses wifi)] event: flow:failed_connect @0.141s, error Software caused connection abort
Relay server otherwise works fine with our QUIC MASQUE clients but not with built-in macOS MASQUE client. Anything I'm missing?
Background
Android phones supporting Wi-Fi Aware 4.0 should be able to connect with iPhones (iOS 26). For testing, we selected two Samsung S25 devices, which support Wi-Fi Aware 4.0.
Issues we are facing
Android as Publisher, iOS as Subscriber.iOS cannot discover the service. Log shows: Discovery: Dropping event, 02:14:60:76:a6:0f missing DCEA attribute.
iOS as Publisher, Android as Subscriber,Android can discover the service.However, the PIN code is not displayed on iOS.
From the packet capture, the publish packet does not contain the DCEA field. However, Android-to-Android devices can still pair normally, and the subsequent PASN packets include the DCEA field. It seems that the Wi-Fi Alliance only requires the DCEA to be present in the PASN packets.
iOS cannot discover Android devices or complete pairing — is this caused by the DCEA field, or by other reasons?
We are using PacketTunnel as system extension to establish vpn tunnel. The flow is like:
Create a PacketTunnelProvide to establish vpn
When tunnel gets connected add excludedRoutes by calling setTunnelNetworkSettings().
Result: The routing table is not getting updated with new excludeRoutes entries.
As per setTunnelNetworkSettings() documentation:
"This function is called by tunnel provider implementations to set the network settings of the tunnel, including IP routes, DNS servers, and virtual interface addresses depending on the tunnel type. Subclasses should not override this method. This method can be called multiple times during the lifetime of a particular tunnel. It is not necessary to call this function with nil to clear out the existing settings before calling this function with a non-nil configuration."
So we believe setTunnelNetworkSettings() should be able to set new excludeRoutes. We could see we are passing correct entries to setTunnelNetworkSettings():
{
tunnelRemoteAddress = 10.192.229.240
DNSSettings = {
protocol = cleartext
server = (
10.192.230.211,
192.168.180.15,
)
matchDomains = (
,
)
matchDomainsNoSearch = NO
}
IPv4Settings = {
configMethod = manual
addresses = (
100.100.100.17,
)
subnetMasks = (
255.255.255.255,
)
includedRoutes = (
{
destinationAddress = 1.1.1.1
destinationSubnetMask = 255.255.255.255
gatewayAddress = 100.100.100.17
},
{
destinationAddress = 2.2.2.0
destinationSubnetMask = 255.255.255.255
gatewayAddress = 100.100.100.17
},
{
destinationAddress = 11.11.11.0
destinationSubnetMask = 255.255.255.0
gatewayAddress = 100.100.100.17
},
)
excludedRoutes = (
{
destinationAddress = 170.114.52.2
destinationSubnetMask = 255.255.255.255
},
)
overridePrimary = NO
}
MTU = 1298
}
The problem is present on macOS Sequoia 15.2.
Is it a known issue? Did anyone else faced this issue?
This is a topic that’s come up a few times on the forums, so I thought I’d write up a summary of the issues I’m aware of. If you have questions or comments, start a new thread in the App & System Services > Networking subtopic and tag it with Network Extension. That way I’ll be sure to see it go by.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Network Extension Provider Packaging
There are two ways to package a network extension provider:
App extension ( appex )
System extension ( sysex )
Different provider types support different packaging on different platforms. See TN3134 Network Extension provider deployment for the details.
Some providers, most notably packet tunnel providers on macOS, support both appex and sysex packaging. Sysex packaging has a number of advantages:
It supports direct distribution, using Developer ID signing.
It better matches the networking stack on macOS. An appex is tied to the logged in user, whereas a sysex, and the networking stack itself, is global to the system as a whole.
Given that, it generally makes sense to package your Network Extension (NE) provider as a sysex on macOS. If you’re creating a new product that’s fine, but if you have an existing iOS product that you want to bring to macOS, you have to account for the differences brought on by the move to sysex packaging. Similarly, if you have an existing sysex product on macOS that you want to bring to iOS, you have to account for the appex packaging. This post summarises those changes.
Keep the following in mind while reading this post:
The information here applies to all NE providers that can be packaged as either an appex or a sysex. When this post uses a specific provider type in an example, it’s just an example.
Unless otherwise noted, any information about iOS also applies to iPadOS, tvOS, and visionOS.
Process Lifecycle
With appex packaging, the system typically starts a new process for each instance of your NE provider. For example, with a packet tunnel provider:
When the users starts the VPN, the system creates a process and then instantiates and starts the NE provider in that process.
When the user stops the VPN, the system stops the NE provider and then terminates the process running it.
If the user starts the VPN again, the system creates an entirely new process and instantiates and starts the NE provider in that.
In contrast, with sysex packaging there’s typically a single process that runs all off the sysex’s NE providers. Returning to the packet tunnel provider example:
When the users starts the VPN, the system instantiates and starts the NE provider in the sysex process.
When the user stops the VPN, the system stops and deallocates the NE provider instances, but leaves the sysex process running.
If the user starts the VPN again, the system instantiates and starts a new instances of the NE provider in the sysex process.
This lifecycle reflects how the system runs the NE provider, which in turn has important consequences on what the NE provider can do:
An appex acts like a launchd agent [1], in that it runs in a user context and has access to that user’s state.
A sysex is effectively a launchd daemon. It runs in a context that’s global to the system as a whole. It does not have access to any single user’s state. Indeed, there might be no user logged in, or multiple users logged in.
The rest of this post explores specific consequences of the NE provider lifecycle.
[1] It’s not actually run as a launchd agent. Rather, there’s a system launchd agent that acts as the host for the app extension.
App Groups
With an app extension, the app extension and its container app run as the same user. Thus it’s trivial to share state between them using an app group container.
Note When talking about extensions on Apple platforms, the container app is the app in which the extension is embedded and the host app is the app using the extension. For network extensions the host app is the system itself.
That’s not the case with a system extension. The system extension runs as root whereas the container app runs an the user who launched it. While both programs can claim access to the same app group, the app group container location they receive will be different. For the system extension that location will be inside the home directory for the root user. For the container app the location will be inside the home directory of the user who launched it.
This does not mean that app groups are useless in a Network Extension app. App groups are also a factor in communicating between the container app and its extensions, the subject of the next section.
IMPORTANT App groups have a long and complex history on macOS. For the full story, see App Groups: macOS vs iOS: Working Towards Harmony.
Communicating with Extensions
With an app extension there are two communication options:
App-provider messages
App groups
App-provider messages are supported by NE directly. In the container app, send a message to the provider by calling sendProviderMessage(_:responseHandler:) method. In the appex, receive that message by overriding the handleAppMessage(_:completionHandler:) method.
An appex can also implement inter-process communication (IPC) using various system IPC primitives. Both the container app and the appex claim access to the app group via the com.apple.security.application-groups entitlement. They can then set up IPC using various APIs, as explain in the documentation for that entitlement.
With a system extension the story is very different. App-provider messages are supported, but they are rarely used. Rather, most products use XPC for their communication. In the sysex, publish a named XPC endpoint by setting the NEMachServiceName property in its Info.plist. Listen for XPC connections on that endpoint using the XPC API of your choice.
Note For more information about the available XPC APIs, see XPC Resources.
In the container app, connect to that named XPC endpoint using the XPC Mach service name API. For example, with NSXPCConnection, initialise the connection with init(machServiceName:options:), passing in the string from NEMachServiceName. To maximise security, set the .privileged flag.
Note XPC Resources has a link to a post that explains why this flag is important.
If the container app is sandboxed — necessary if you ship on the Mac App Store — then the endpoint name must be prefixed by an app group ID that’s accessible to that app, lest the App Sandbox deny the connection. See app groups documentation for the specifics.
When implementing an XPC listener in your sysex, keep in mind that:
Your sysex’s named XPC endpoint is registered in the global namespace. Any process on the system can open a connection to it [1]. Your XPC listener must be prepared for this. If you want to restrict connections to just your container app, see XPC Resources for a link to a post that explains how to do that.
Your sysex only gets one named XPC endpoint, and thus one XPC listener. If your sysex includes multiple NE providers, take that into account when you design your XPC protocol.
[1] Assuming that connection isn’t blocked by some other mechanism, like the App Sandbox.
Inter-provider Communication
A sysex can include multiple types of NE providers. For example, a single sysex might include a content filter and a DNS proxy provider. In that case the system instantiates all of the NE providers in the same sysex process. These instances can communicate without using IPC, for example, by storing shared state in global variables (with suitable locking, of course).
It’s also possible for a single container app to contain multiple sysexen, each including a single NE provider. In that case the system instantiates the NE providers in separate processes, one for each sysex. If these providers need to communicate, they have to use IPC.
In the appex case, the system instantiates each provider in its own process. If two providers need to communicate, they have to use IPC.
Managing Secrets
An appex runs in a user context and thus can store secrets, like VPN credentials, in the keychain. On macOS this includes both the data protection keychain and the file-based keychain. It can also use a keychain access group to share secrets with its container app. See Sharing access to keychain items among a collection of apps.
Note If you’re not familiar with the different types of keychain available on macOS, see TN3137 On Mac keychain APIs and implementations.
A sysex runs in the global context and thus doesn’t have access to user state. It also doesn’t have access to the data protection keychain. It must use the file-based keychain, and specifically the System keychain. That means there’s no good way to share secrets with the container app.
Instead, do all your keychain operations in the sysex. If the container app needs to work with a secret, have it pass that request to the sysex via IPC. For example, if the user wants to use a digital identity as a VPN credential, have the container app get the PKCS#12 data and password and then pass that to the sysex so that it can import the digital identity into the keychain.
Memory Limits
iOS imposes strict memory limits an NE provider appexen [1]. macOS imposes no memory limits on NE provider appexen or sysexen.
[1] While these limits are not documented officially, you can get a rough handle on the current limits by reading the posts in this thread.
Frameworks
If you want to share code between a Mac app and its embedded appex, use a structure like this:
MyApp.app/
Contents/
MacOS/
MyApp
PlugIns/
MyExtension.appex/
Contents/
MacOS/
MyExtension
…
Frameworks/
MyFramework.framework/
…
There’s one copy of the framework, in the app’s Frameworks directory, and both the app and the appex reference it.
This approach works for an appex because the system always loads the appex from your app’s bundle. It does not work for a sysex. When you activate a sysex, the system copies it to a protected location. If that sysex references a framework in its container app, it will fail to start because that framework isn’t copied along with the sysex.
The solution is to structure your app like this:
MyApp.app/
Contents/
MacOS/
MyApp
Library/
SystemExtensions/
MyExtension.systemextension/
Contents/
MacOS/
MyExtension
Frameworks/
MyFramework.framework/
…
…
That is, have both the app and the sysex load the framework from the sysex’s Frameworks directory. When the system copies the sysex to its protected location, it’ll also copy the framework, allowing the sysex to load it.
To make this work you have to change the default rpath configuration set up by Xcode. Read Dynamic Library Standard Setup for Apps to learn how that works and then tweak things so that:
The framework is embedded in the sysex, not the container app.
The container app has an additional LC_RPATH load command for the sysex’s Frameworks directory (@executable_path/../Library/SystemExtensions/MyExtension.systemextension/Contents/Frameworks).
The sysex’s LC_RPATH load command doesn’t reference the container app’s Frameworks directory (@executable_path/../../../../Frameworks) but instead points to the sysex’s Framweorks directory (@executable_path/../Frameworks).
I'm developing in Swift and working on parsing DNS queries. I'm considering using dns_parse_packet, but I noticed that dns_util is deprecated (although it still seems to work in my limited testing).
As far as I know, there isn’t a built-in replacement for this. Is that correct?
On a related note, are there any libraries available for parsing TLS packets—specifically the ClientHello message to extract the Server Name Indication (SNI)—instead of relying on my own implementation?
Related to this post.
For important background information, read Extra-ordinary Networking before reading this.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Broadcasts and Multicasts, Hints and Tips
I regularly see folks struggle with broadcasts and multicasts on Apple platforms. This post is my attempt to clear up some of the confusion.
This post covers both IPv4 and IPv6. There is, however, a key difference. In IPv4, broadcasts and multicasts are distinct concepts. In contrast, IPv6 doesn’t support broadcast as such; rather, it treats broadcasts as a special case of multicasts. IPv6 does have an all nodes multicast address, but it’s rarely used.
Before reading this post, I suggest you familiarise yourself with IP addresses in general. A good place to start is The Fount of All Knowledge™.
Service Discovery
A lot of broadcast and multicast questions come from folks implementing their own service discovery protocol. I generally recommend against doing that, for the reasons outlined in the Service Discovery section of Don’t Try to Get the Device’s IP Address.
There are, however, some good reasons to implement a custom service discovery protocol. For example, you might be working with an accessory that only supports this custom protocol [1]. If you must implement your own service discovery protocol, read this post and also read the advice in Don’t Try to Get the Device’s IP Address.
IMPORTANT Sometimes I see folks implementing their own version of mDNS. This is almost always a mistake:
If you’re using third-party tooling that includes its own mDNS implementation, it’s likely that this tooling allows you to disable that implementation and instead rely on the Bonjour support that’s built-in to all Apple platforms.
If you’re doing some weird low-level thing with mDNS or DNS-SD, it’s likely that you can do that with the low-level DNS-SD API.
[1] And whose firmware you can’t change! I talk more about this in Working with a Wi-Fi Accessory.
API Choice
Broadcasts and multicasts typically use UDP [1]. TN3151 Choosing the right networking API describes two recommended UDP APIs:
Network framework
BSD Sockets
Our general advice is to prefer Network framework over BSD Sockets, but UDP broadcasts and multicasts are an exception to that rule. Network framework has very limited UDP broadcast support. And while it’s support for UDP multicasts is less limited, it’s still not sufficient for all UDP applications. In cases where Network framework is not sufficient, BSD Sockets is your only option.
[1] It is possible to broadcast and multicast at the Ethernet level, but I almost never see questions about that.
UDP Broadcasts in Network Framework
Historically I’ve claimed that Network framework was useful for UDP broadcasts is very limited circumstances (for example, in the footnote on this post). I’ve since learnt that this isn’t the case. Or, more accurately, this support is so limited (r. 122924701) as to be useless in practice.
For the moment, if you want to work with UDP broadcasts, your only option is BSD Sockets.
UDP Multicasts in Network Framework
Network framework supports UDP multicast using the NWConnectionGroup class with the NWMulticastGroup group descriptor. This support has limits. The most significant limit is that it doesn’t support broadcasts; it’s for multicasts only.
Note This only relevant to IPv4. Remember that IPv6 doesn’t support broadcasts as a separate concept.
There are other limitations, but I don’t have a good feel for them. I’ll update this post as I encounter issues.
Local Network Privacy
Some Apple platforms support local network privacy. This impacts broadcasts and multicasts in two ways:
Broadcasts and multicasts require local network access, something that’s typically granted by the user.
Broadcasts and multicasts are limited by a managed entitlement (except on macOS).
TN3179 Understanding local network privacy has lots of additional info on this topic, including the list of platforms to which it applies.
Send, Receive, and Interfaces
When you broadcast or multicast, there’s a fundamental asymmetry between send and receive:
You can reasonable receive datagrams on all broadcast-capable interfaces.
But when you send a datagram, it has to target a specific interface.
The sending behaviour is the source of many weird problems. Consider the IPv4 case. If you send a directed broadcast, you can reasonably assume it’ll be routed to the correct interface based on the network prefix. But folks commonly send an all-hosts broadcast (255.255.255.255), and it’s not obvious what happens in that case.
Note If you’re unfamiliar with the terms directed broadcast and all-hosts broadcast, see IP address.
The exact rules for this are complex, vary by platform, and can change over time. For that reason, it’s best to write your broadcast code to be interface specific. That is:
Identify the interfaces on which you want to work.
Create a socket per interface.
Bind that socket to that interface.
Note Use the IP_BOUND_IF (IPv4) or IPV6_BOUND_IF (IPv6) socket options rather than binding to the interface address, because the interface address can change over time.
Extra-ordinary Networking has links to other posts which discuss these concepts and the specific APIs in more detail.
Miscellaneous Gotchas
A common cause of mysterious broadcast and multicast problems is folks who hard code BSD interface names, like en0. Doing that might work for the vast majority of users but then fail in some obscure scenarios.
BSD interface names are not considered API and you must not hard code them. Extra-ordinary Networking has links to posts that describe how to enumerate the interface list and identify interfaces of a specific type.
Don’t assume that there’ll be only one interface of a given type. This might seem obviously true, but it’s not. For example, our platforms support peer-to-peer Wi-Fi, so each device has multiple Wi-Fi interfaces.
When sending a broadcast, don’t forget to enable the SO_BROADCAST socket option.
If you’re building a sandboxed app on the Mac, working with UDP requires both the com.apple.security.network.client and com.apple.security.network.server entitlements.
Some folks reach for broadcasts or multicasts because they’re sending the same content to multiple devices and they believe that it’ll be faster than unicasts. That’s not true in many cases, especially on Wi-Fi. For more on this, see the Broadcasts section of Wi-Fi Fundamentals.
Snippets
To send a UDP broadcast:
func broadcast(message: Data, to interfaceName: String) throws {
let fd = try FileDescriptor.socket(AF_INET, SOCK_DGRAM, 0)
defer { try! fd.close() }
try fd.setSocketOption(SOL_SOCKET, SO_BROADCAST, 1 as CInt)
let interfaceIndex = if_nametoindex(interfaceName)
guard interfaceIndex > 0 else { throw … }
try fd.setSocketOption(IPPROTO_IP, IP_BOUND_IF, interfaceIndex)
try fd.send(data: message, to: ("255.255.255.255", 2222))
}
Note These snippet uses the helpers from Calling BSD Sockets from Swift.
To receive UDP broadcasts:
func receiveBroadcasts(from interfaceName: String) throws {
let fd = try FileDescriptor.socket(AF_INET, SOCK_DGRAM, 0)
defer { try! fd.close() }
let interfaceIndex = if_nametoindex(interfaceName)
guard interfaceIndex > 0 else { fatalError() }
try fd.setSocketOption(IPPROTO_IP, IP_BOUND_IF, interfaceIndex)
try fd.setSocketOption(SOL_SOCKET, SO_REUSEADDR, 1 as CInt)
try fd.setSocketOption(SOL_SOCKET, SO_REUSEPORT, 1 as CInt)
try fd.bind("0.0.0.0", 2222)
while true {
let (data, (sender, port)) = try fd.receiveFrom()
…
}
}
IMPORTANT This code runs synchronously, which is less than ideal. In a real app you’d run the receive asynchronously, for example, using a Dispatch read source. For an example of how to do that, see this post.
If you need similar snippets for multicast, lemme know. I’ve got them lurking on my hard disk somewhere (-:
Other Resources
Apple’s official documentation for BSD Sockets is in the man pages. See Reading UNIX Manual Pages. Of particular interest are:
setsockopt man page
ip man page
ip6 man page
If you’re not familiar with BSD Sockets, I strongly recommend that you consult third-party documentation for it. BSD Sockets is one of those APIs that looks simple but, in reality, is ridiculously complicated. That’s especially true if you’re trying to write code that works on BSD-based platforms, like all of Apple’s platforms, and non-BSD-based platforms, like Linux.
I specifically recommend UNIX Network Programming, by Stevens et al, but there are lots of good alternatives.
https://unpbook.com
Revision History
2025-09-01 Fixed a broken link.
2025-01-16 First posted.
At WWDC 2015 Apple announced two major enhancements to the Network Extension framework:
Network Extension providers — These are app extensions that let you insert your code at various points within the networking stack, including:
Packet tunnels via NEPacketTunnelProvider
App proxies via NEAppProxyProvider
Content filters via NEFilterDataProvider and NEFilterControlProvider
Hotspot Helper (NEHotspotHelper) — This allows you to create an app that assists the user in navigating a hotspot (a Wi-Fi network where the user must interact with the network in order to get access to the wider Internet).
Originally, using any of these facilities required authorisation from Apple. Specifically, you had to apply for, and be granted access to, a managed capability. In Nov 2016 this policy changed for Network Extension providers. Any developer can now use the Network Extension provider capability like they would any other capability.
There is one exception to this rule: Network Extension app push providers, introduced by iOS 14 in 2020, still requires that Apple authorise the use of a managed capability. To apply for that, follow the link in Local push connectivity.
Also, the situation with Hotspot Helpers remains the same: Using a Hotspot Helper, requires that Apple authorise that use via a managed capability. To apply for that, follow the link in Hotspot helper.
IMPORTANT Pay attention to this quote from the documentation:
NEHotspotHelper is only useful for hotspot integration. There are
both technical and business restrictions that prevent it from being
used for other tasks, such as accessory integration or Wi-Fi based
location.
The rest of this document answers some frequently asked questions about the Nov 2016 change.
#1 — Has there been any change to the OS itself?
No, this change only affects the process by which you get the capabilities you need in order to use existing Network Extension framework facilities. Previously these were managed capabilities, meaning their use was authorised by Apple. Now, except for app push providers and Hotspot Helper, you can enable the necessary capabilities using Xcode’s Signing & Capabilities editor or the Developer website.
IMPORTANT Some Network Extension providers have other restrictions on their use. For example, a content filter can only be used on a supervised device. These restrictions are unchanged. See TN3134 Network Extension provider deployment for the details.
#2 — How exactly do I enable the Network Extension provider capability?
In the Signing & Capabilities editor, add the Network Extensions capability and then check the box that matches the provider you’re creating.
In the Certificates, Identifiers & Profiles section of the Developer website, when you add or edit an App ID, you’ll see a new capability listed, Network Extensions. Enable that capability in your App ID and then regenerate the provisioning profiles based on that App ID.
A newly generated profile will include the com.apple.developer.networking.networkextension entitlement in its allowlist; this is an array with an entry for each of the supported Network Extension providers. To confirm that this is present, dump the profile as shown below.
$ security cms -D -i NETest.mobileprovision
…
<plist version="1.0">
<dict>
…
<key>Entitlements</key>
<dict>
<key>com.apple.developer.networking.networkextension</key>
<array>
<string>packet-tunnel-provider</string>
<string>content-filter-provider</string>
<string>app-proxy-provider</string>
… and so on …
</array>
…
</dict>
…
</dict>
</plist>
#3 — I normally use Xcode’s Signing & Capabilities editor to manage my entitlements. Do I have to use the Developer website for this?
No. Xcode 11 and later support this capability in the Signing & Capabilities tab of the target editor (r. 28568128 ).
#4 — Can I still use Xcode’s “Automatically manage signing” option?
Yes. Once you modify your App ID to add the Network Extension provider capability, Xcode’s automatic code signing support will include the entitlement in the allowlist of any profiles that it generates based on that App ID.
#5 — What should I do if I previously applied for the Network Extension provider managed capability and I’m still waiting for a reply?
Consider your current application cancelled, and use the new process described above.
#6 — What should I do if I previously applied for the Hotspot Helper managed capability and I’m still waiting for a reply?
Apple will continue to process Hotspot Helper managed capability requests and respond to you in due course.
#7 — What if I previously applied for both Network Extension provider and Hotspot Helper managed capabilities?
Apple will ignore your request for the Network Extension provider managed capability and process it as if you’d only asked for the Hotspot Helper managed capability.
#8 — On the Mac, can Developer ID apps host Network Extension providers?
Yes, but there are some caveats:
This only works on macOS 10.15 or later.
Your Network Extension provider must be packaged as a system extension, not an app extension.
You must use the *-systemextension values for the Network Extension entitlement (com.apple.developer.networking.networkextension).
For more on this, see Exporting a Developer ID Network Extension.
#9 — After moving to the new process, my app no longer has access to the com.apple.managed.vpn.shared keychain access group. How can I regain that access?
Access to this keychain access group requires another managed capability. If you need that, please open a DTS code-level support request and we’ll take things from there.
IMPORTANT This capability is only necessary if your VPN supports configuration via a configuration profile and needs to access credentials from that profile (as discussed in the Profile Configuration section of the NETunnelProviderManager Reference). Many VPN apps don’t need this facility.
Opening a DTS tech support incident (TSI) will consume a TSI asset. However, as this is not a technical issue but an administrative one, we’ll assign a replacement TSI asset back to your account.
If you were previously granted the Network Extension managed capability (via the process in place before Nov 2016), make sure you mention that; restoring your access to the com.apple.managed.vpn.shared keychain access group should be straightforward in that case.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Revision History
2025-09-12 Adopted the code-level support request terminology. Made other minor editorial changes.
2023-01-11 Added a discussion of Network Extension app push providers. Added a link to Exporting a Developer ID Network Extension. Added a link to TN3134. Made significant editorial changes.
2020-02-27 Fixed the formatting. Updated FAQ#3. Made minor editorial changes.
2020-02-16 Updated FAQ#8 to account for recent changes. Updated FAQ#3 to account for recent Xcode changes. Made other editorial changes.
2016-01-25 Added FAQ#9.
2016-01-6 Added FAQ#8.
2016-11-11 Added FAQ#5, FAQ#6 and FAQ#7.
2016-11-11 First posted.
MINI M2 Apache httpd stopped serving with this in log: "bug_type":"312","os_version":"macOS 15.2 (24C5079e)"} {"issueCategory":"hitch","logType":"Tailspin","uploadAttemptCount":0,
Sequoia 15.2 Beta Server runs about 2 hours and then need to reboot computer to restart to server remote viewers. Brew Service ReStart and sudo apachectl graceful restart server for localhost but they will not restart server for remote viewers.
Hello,
I'd like to find out if macOS Sequoia's MAC Address randomization affects the data (specifically, MAC addresses) we receive from I/O Kit.
For context, I'd like to find out if it affects my Mac App Store receipt validation code in any way.
Thank you,
– Matthias
Topic:
App & System Services
SubTopic:
Networking
Tags:
macOS
IOKit
App Store Receipts
Mac App Store
I am developing a USB networking accessory using the CDC ECM or NCM protocol and I would like to know what are the MacOS and iPadOS requirements to connect to such a device.
I have a prototype CDC ECM device developed that uses static IPv4 addressing which I can connect to an Arch Linux host and ping, but I am unable to have the same success from my Mac Studio M1 running Sequoia 15.1.1. The device shows up under 'Other Services' with 'Not connected' status, whether I leave it with the default settings or change it to 'Configure IPv4 -> Manually' and then set the appropriate IP address / Subnet mask / Router.
From a discussion on Github, it seems that the ECM device must support NetworkConnection notification in order to work with MacOS. Can you point me to where this is documented and whether there are other expectations/requirements around USB network adapters?
My end goal is to make an embedded device that communicates to MacOS and iPadOS devices/apps over USB CDC NCM with a simple UDP socket listener.
Thank you in advance for any help you can provide.
IMPORTANT This FAQ has been replaced by TN3179 Understanding local network privacy. I’m leaving this post in place as a historical curiosity, but please consult the technote going forward.
I regularly get asked questions about local network privacy. This is my attempt to collect together the answers for the benefit of all. Before you delve into the details, familiarise yourself with the basics by watching WWDC 2020 Session 10110 Support local network privacy in your app.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Local Network Privacy FAQ
With local network privacy, any app that wants to interact with devices on your network must ask for permission the first time that it attempts that access. Local network privacy is implemented on iOS, iPadOS, visionOS, and macOS. It’s not implemented on other platforms, most notably tvOS.
IMPORTANT macOS 15 (currently in beta) introduced local network privacy support to the Mac. WWDC 2024 Session 10123 What’s new in privacy is the official announcement. This works much like it does on iOS, but there are some subtle differences. I’ll update this FAQ as I gain more experience with this change.
Some common questions about local network privacy are:
FAQ-1 What is a local network?
FAQ-2 What operations require local network access?
FAQ-3 What operations require the multicast entitlement?
FAQ-4 Do I need the multicast entitlement?
FAQ-5 I’ve been granted the multicast entitlement; how do I enable it?
FAQ-6 Can App Clips access the local network?
FAQ-7 How does local network privacy work with app extensions?
FAQ-8 How do I explicitly trigger the local network privacy alert?
FAQ-9 How do I tell whether I’ve been granted local network access?
FAQ-10 How do I use the unsatisfied reason property?
FAQ-11 Do I need a local network usage description property?
FAQ-12 Can I test on the simulator?
FAQ-13 Once my app has displayed the local network privacy alert, how can I reset its state so that it shows again?
FAQ-14 How do I map my Multipeer Connectivity service type to an entry in the Bonjour services property?
FAQ-15 My app presents the local network privacy alert unexpectedly. Is there a way to track down the cause?
FAQ-16 On a small fraction of devices my app fails to present the local network privacy alert. What’s going on?
FAQ-17 Why does local network privacy get confused when I install two variants of my app?
FAQ-18 Can my app trigger the local network privacy alert when the device is on WWAN?
Revision History
2024-10-31 Added a link to this FAQ’s replacement, TN3179 Understanding local network privacy.
2024-07-22 Added a callout explaining that local network privacy is now an issue on macOS.
2023-10-31 Fixed a bug in the top-level FAQ that mistakenly removed some recent changes. Added FAQ-18.
2023-10-19 Added a preamble to clarify that local network privacy is only relevant on specific platforms.
2023-09-14 Added FAQ-17.
2023-08-29 Added FAQ-16.
2023-03-13 Added connecting a UDP socket to FAQ-2.
2022-10-04 Added screen shots to FAQ-11.
2022-09-22 Fixed the pointer from FAQ-9 to FAQ-10.
2022-09-19 Updated FAQ-3 to cover iOS 16 changes. Made other minor editorial changes.
2020-11-12 Made a minor tweak to FAQ-9.
2020-10-17 Added FAQ-15. Added a second suggestion to FAQ-13.
2020-10-16 First posted.
Is Apple's Wi-Fi Aware certified by the Wi-Fi Alliance?
Is there any non-compliance of Apple's Wi-Fi Aware with the Wi-Fi Alliance standards?
Does Apple have a roadmap to switch AWDL to Wi-Fi Aware?
Does Apple have plans to adopt Wi-Fi Aware in Mac computers?
Android phones supporting Wi-Fi Aware 4.0 should be able to connect with iPhones (iOS 26). For testing, we selected two Samsung S25 devices, which support Wi-Fi Aware 4.0.
Issues we are facing
Android as Publisher, iOS as Subscriber, iOS cannot discover the service. Log shows: Discovery: Dropping event, 02:14:60:76:a6:0f missing DCEA attribute.
iOS as Publisher, Android as Subscriber.Android can discover the service.However, the PIN code is not displayed on iOS.
From the packet capture, the publish packet does not contain the DCEA field. However, Android-to-Android devices can still pair normally, and the subsequent PASN packets include the DCEA field. It seems that the Wi-Fi Alliance only requires the DCEA to be present in the PASN packets.
iOS cannot discover Android devices or complete pairing — is this caused by the DCEA field, or by other reasons?
Topic:
App & System Services
SubTopic:
Networking
I would like to test running some Thread Networking code on my MacOS machine:
import ThreadNetwork
let client = THClient()
let bIsPreferredAvailable = await client.isPreferredAvailable()
but I get some errors when trying to create an instance of the THClient class:
Client: -[THClient connectToXPCService]_block_invoke - CTCS XPC Client is interrupted.
Client: -[THClient getConnectionEntitlementValidity]_block_invoke - clientProxyWithErrorHandler Error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.ThreadNetwork.xpc" UserInfo={NSDebugDescription=connection to service named com.apple.ThreadNetwork.xpc}
Client: -[THClient init] - XPC Client Init Failed
Invalidating XPC connection.
Client: -[THClient getConnectionEntitlementValidity]_block_invoke - clientProxyWithErrorHandler Error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.ThreadNetwork.xpc" UserInfo={NSDebugDescription=connection to service named com.apple.ThreadNetwork.xpc}
How can I get the code to run?
This post is part of the Local Network Privacy FAQ.
What operations require local network access?
The general rule is that outgoing traffic to a local network address requires that the user grant your app local network access. Common scenarios include:
Making an outgoing TCP connection — yes
Listening for and accepting incoming TCP connections — no
Sending a UDP unicast — yes
Sending a UDP multicast — yes
Sending a UDP broadcast — yes
Connecting a UDP socket — yes
Receiving an incoming UDP unicast — no
Receiving an incoming UDP multicast — yes
Receiving an incoming UDP broadcast — yes
These TCP and UDP checks are done at the lowest levels of the system and thus apply to all networking APIs. This includes Network framework, BSD Sockets, NSStream, and NSURLSession, and any other protocols that you layer on top of those.
IMPORTANT Receiving an incoming UDP multicast or broadcast does not currently require local network access but, because we hope to change that in a future update, our advice right now is that you write your code as if did (r. 69792887, 70017649).
Resolving link-local DNS names (those ending with local, per RFC 6762) requires local network access. Again, this check applies to a wide variety of APIs including <dns_sd.h>, <net_db.h>, Network framework, NSStream, and NSURLSession.
Finally, all Bonjour operations require local network access:
Registering a service with Bonjour — yes
Browsing for Bonjour services — yes
Resolving a Bonjour service — yes
Again, these checks apply to all APIs that use Bonjour, including <dns_sd.h>, Network framework, NSNetService, and Multipeer Connectivity.
Note You must declare the Bonjour service types you use in your Info.plist. See FAQ-14 How do I map my Multipeer Connectivity service type to an entry in the Bonjour services property? for details.
Bonjour-based services where you don’t see any details of the network do not require local network access. These include:
AirPlay — no
Printing via UIKit — no
Back to the FAQ
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 a peer receives a peer identifier from a connection, it checks for a duplicate. If it finds one, it compares the peer identifiers and then chooses a connection to drop based on that comparison:
if local peer identifier > remote peer identifier then
drop outgoing connection
else
drop incoming connection
end if
So, peer A drops its incoming connection and peer B drops its outgoing connection. Et voilà!
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 that 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.
Note If you’re targeting Apple TV, check out the DeviceDiscoveryUI framework.
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 use the peer identifier as the service name. Whether that’s a good option depends on the user experience of your product:
Some products present a list of remote peers and have the user choose from that list. In that case it’s best to stick with the user-assigned device name, because that’s what the user will recognise.
Some products automatically connect to services as they discover them. In that case it’s fine to use the peer identifier as the service name, because the user won’t see it anyway.
If you stick with the user-assigned device name, consider advertising the peer identifier in your TXT record. See Discovery TXT records.
IMPORTANT Using a peer identifier in your service name or TXT record is a heuristic to reduce the number of duplicate connections. Don’t rely on it for correctness. Rather, deduplicate connections using the process described in Create a peer identifier.
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-04-11 Added some advice as to whether to use the peer identifier in your service name. Expanded the discussion of how to deduplicate connections in a star network architecture.
2025-03-20 Added a link to the DeviceDiscoveryUI framework to the Discovery UI section. Made other minor editorial changes.
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.
IMPORTANT The resume rate limiter is now covered by the official documentation. See Use background sessions efficiently within Downloading files in the background. So, the following is here purely for historical perspective.
NSURLSession’s background session support on iOS includes a resume rate limiter. This limiter exists to prevent apps from abusing the background session support in order to run continuously in the background. It works as follows:
nsurlsessiond (the daemon that does all the background session work) maintains a delay value for your app.
It doubles that delay every time it resumes (or relaunches) your app.
It resets that delay to 0 when the user brings your app to the front.
It also resets the delay to 0 if the delay period elapses without it having resumed your app.
When your app creates a new task while it is in the background, the task does not start until that delay has expired.
To understand the impact of this, consider what happens when you download 10 resources. If you pass them to the background session all at once, you see something like this:
Your app creates tasks 1 through 10 in the background session.
nsurlsessiond starts working on the first few tasks.
As tasks complete, nsurlsessiond starts working on subsequent ones.
Eventually all the tasks complete and nsurlsessiond resumes your app.
Now consider what happens if you only schedule one task at a time:
Your app creates task 1.
nsurlsessiond starts working on it.
When it completes, nsurlsessiond resumes your app.
Your app creates task 2.
nsurlsessiond delays the start of task 2 a little bit.
nsurlsessiond starts working on task 2.
When it completes, nsurlsessiond resumes your app.
Your app creates task 3.
nsurlsessiond delays the start of task 3 by double the previous amount.
nsurlsessiond starts working on task 3.
When it completes, nsurlsessiond resumes your app.
Steps 8 through 11 repeat, and each time the delay doubles. Eventually the delay gets so large that it looks like your app has stopped making progress.
If you have a lot of tasks to run then you can mitigate this problem by starting tasks in batches. That is, rather than start just one task in step 1, you would start 100. This only helps up to a point. If you have thousands of tasks to run, you will eventually start seeing serious delays. In that case it’s much better to change your design to use fewer, larger transfers.
Note All of the above applies to iOS 8 and later. Things worked differently in iOS 7. There’s a post on DevForums that explains the older approach.
Finally, keep in mind that there may be other reasons for your task not starting. Specifically, if the task is flagged as discretionary (because you set the discretionary flag when creating the task’s session or because the task was started while your app was in the background), the task may be delayed for other reasons (low power, lack of Wi-Fi, and so on).
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
(r. 22323366)
I am developing an application that processes a video file stored on a server. I use URLSessionDataTask with a delegate handler to download the file.
It is not necessary to download the entire file at once. Instead, I can load small chunks of the file as needed. This approach helps minimize memory consumption.
I am trying to design a network layer that supports this behavior. Ideally, I would like to have an interface similar to:
func readMoreData(length: Int) async throws -> Data
Problems I Encountered:
It seems that URLSessionDataTask does not allow controlling how many bytes will be downloaded. It always downloads the entire request.
If I call suspend on URLSessionDataTask, the network activity does not stop, and the file keeps downloading.
If I upgrade the dataTask to a StreamTask, the file still downloads, though reading bytes can be done through the StreamTask API.
I would prefer behavior similar to AsyncHTTPClient (a Swift Server library) or Network Framework. These frameworks allow controlling the number of bytes downloaded at a time. Unfortunately, they do not fit the specific requirements of my project.
Am I correct in understanding that controlling the download process is not possible with URLSessionDataTask?
As a possible solution, I am considering using HTTP Range Requests, though this would increase the number of additional server requests, which I would like to avoid.
Topic:
App & System Services
SubTopic:
Networking
Hello,
I have a very basic quic client implementation. When you run this code with some basic quic server, you will see that we can't get a handle to stream identifier 0, but behavior is actually different when we use URLSession/URLRequest, and I can see that some information can be sent over the wire for stream identifier 0 with that implementation.
You can find both code below I'm using to test this.
I'd like to get more info about how I can use stream identifier 0 with NWMultiplexGroup, if I can't use it with NWMultiplexGroup, I need a workaround to use stream with id 0 and use multiple streams over the same connection.
import Foundation
import Network
let dispatchQueue = DispatchQueue(label: "quicConnectionQueue")
let incomingStreamQueue = DispatchQueue(label: "quicIncStreamsQueue")
let outgoingStreamQueue = DispatchQueue(label: "quicOutStreamsQueue")
let quicOptions = NWProtocolQUIC.Options()
quicOptions.alpn = ["test"]
sec_protocol_options_set_verify_block(quicOptions.securityProtocolOptions, { (sec_prot_metadata, sec_trust, complete_callback) in
complete_callback(true)
}, dispatchQueue)
let parameters = NWParameters(quic: quicOptions);
let multiplexGroup = NWMultiplexGroup(to: NWEndpoint.hostPort(host: "127.0.0.1", port: 5000))
let connectionGroup = NWConnectionGroup(with: multiplexGroup, using: parameters)
connectionGroup.stateUpdateHandler = { newState in
switch newState {
case .ready:
print("Connected using QUIC!")
let _ = createNewStream(connGroup: connectionGroup, content: "First Stream")
let _ = createNewStream(connGroup: connectionGroup, content: "Second Stream")
break
default:
print("Default hit: newState: \(newState)")
}
}
connectionGroup.newConnectionHandler = { newConnection in
// Set state update handler on incoming stream
newConnection.stateUpdateHandler = { newState in
// Handle stream states
}
// Start the incoming stream
newConnection.start(queue: incomingStreamQueue)
}
connectionGroup.start(queue: dispatchQueue)
sleep(50)
func createNewStream(connGroup: NWConnectionGroup, content: String) -> NWConnection? {
let stream = NWConnection(from: connectionGroup)
stream?.stateUpdateHandler = { streamState in
switch streamState {
case .ready:
stream?.send(content: content.data(using: .ascii), completion: .contentProcessed({ error in
print("Send completed! Error: \(String(describing: error))")
}))
print("Sent data!")
printStreamId(stream: stream)
break
default:
print("Default hit: streamState: \(streamState)")
}
}
stream?.start(queue: outgoingStreamQueue)
return stream
}
func printStreamId(stream: NWConnection?)
{
let streamMetadata = stream?.metadata(definition: NWProtocolQUIC.definition) as? NWProtocolQUIC.Metadata
print("stream Identifier: \(String(describing: streamMetadata?.streamIdentifier))")
}
URLSession/URLRequest code:
import Foundation
var networkManager = NetworkManager()
networkManager.testHTTP3Request()
sleep(5)
class NetworkManager: NSObject, URLSessionDataDelegate {
private var session: URLSession!
private var operationQueue = OperationQueue()
func testHTTP3Request() {
if self.session == nil {
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
self.session = URLSession(configuration: config, delegate: self, delegateQueue: operationQueue)
}
let urlStr = "https://localhost:5000"
let url = URL(string: urlStr)!
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
request.assumesHTTP3Capable = true
self.session.dataTask(with: request) { (data, response, error) in
if let error = error as NSError? {
print("task transport error \(error.domain) / \(error.code)")
return
}
guard let data = data, let response = response as? HTTPURLResponse else {
print("task response is invalid")
return
}
guard 200 ..< 300 ~= response.statusCode else {
print("task response status code is invalid; received \(response.statusCode), but expected 2xx")
return
}
print("task finished with status \(response.statusCode), bytes \(data.count)")
}.resume()
}
}
extension NetworkManager {
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
let protocols = metrics.transactionMetrics.map { $0.networkProtocolName ?? "-" }
print("protocols: \(protocols)")
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.serverTrust == nil {
completionHandler(.useCredential, nil)
} else {
let trust: SecTrust = challenge.protectionSpace.serverTrust!
let credential = URLCredential(trust: trust)
completionHandler(.useCredential, credential)
}
}
}
This issue has cropped up many times here on DevForums. Someone recently opened a DTS tech support incident about it, and I used that as an opportunity to post a definitive response here.
If you have questions or comments about this, start a new thread and tag it with Network so that I see it.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
iOS Network Signal Strength
The iOS SDK has no general-purpose API that returns Wi-Fi or cellular signal strength in real time. Given that this has been the case for more than 10 years, it’s safe to assume that it’s not an accidental omission but a deliberate design choice.
For information about the Wi-Fi APIs that are available on iOS, see TN3111 iOS Wi-Fi API overview.
Network performance
Most folks who ask about this are trying to use the signal strength to estimate network performance. This is a technique that I specifically recommend against. That’s because it produces both false positives and false negatives:
The network signal might be weak and yet your app has excellent connectivity. For example, an iOS device on stage at WWDC might have terrible WWAN and Wi-Fi signal but that doesn’t matter because it’s connected to the Ethernet.
The network signal might be strong and yet your app has very poor connectivity. For example, if you’re on a train, Wi-Fi signal might be strong in each carriage but the overall connection to the Internet is poor because it’s provided by a single over-stretched WWAN.
The only good way to determine whether connectivity is good is to run a network request and see how it performs. If you’re issuing a lot of requests, use the performance of those requests to build a running estimate of how well the network is doing. Indeed, Apple practices what we preach here: This is exactly how HTTP Live Streaming works.
Remember that network performance can change from moment to moment. The user’s train might enter or leave a tunnel, the user might step into a lift, and so on. If you build code to estimate the network performance, make sure it reacts to such changes.
Keeping all of the above in mind, iOS 26 beta has two new APIs related to this issue:
Network framework now offers a linkQuality property. See this post for my take on how to use this effectively.
The WirelessInsights framework can notify you of anticipated WWAN condition changes.
But what about this code I found on the ’net?
Over the years various folks have used various unsupported techniques to get around this limitation. If you find code on the ’net that, say, uses KVC to read undocumented properties, or grovels through system logs, or walks the view hierarchy of the status bar, don’t use it. Such techniques are unsupported and, assuming they haven’t broken yet, are likely to break in the future.
But what about Hotspot Helper?
Hotspot Helper does have an API to read Wi-Fi signal strength, namely, the signalStrength property. However, this is not a general-purpose API. Like the rest of Hotspot Helper, this is tied to the specific use case for which it was designed. This value only updates in real time for networks that your hotspot helper is managing, as indicated by the isChosenHelper property.
But what about MetricKit?
MetricKit is so cool. Amongst other things, it supports the MXCellularConditionMetric payload, which holds a summary of the cellular conditions while your app was running. However, this is not a real-time signal strength value.
But what if I’m working for a carrier?
This post is about APIs in the iOS SDK. If you’re working for a carrier, discuss your requirements with your carrier’s contact at Apple.
Revision History
2025-07-02 Updated to cover new features in the iOS 16 beta. Made other minor editorial changes.
2022-12-01 First posted.