iOS Development environment
Xcode 16.4, macOS 15.6.1 (24G90)
Run-time configuration: iOS 17.2+
Short Description
After having successfully established an NWConnection (either as UDP or TCP), and subsequently receiving the error code:
UDP Connection failed: 57 The operation couldn't be completed. (Network.NWError error 57 - Socket is not connected), available Interfaces: [enO]
via
NWConnection.stateUpdateHandler = { (newState) in ... } while newState == .failed
the data connection does not restart by itself once cellular (RF) telephony coverage is established again.
Detailed Description
Context: my app has a continuous cellular data connection while in use. Either a UDP or a TCP connection is established depending on the user settings.
The setup data connection works fine until the data connection gets disconnected by loss of connection to a available cellular phone base station. This disconnection simply occurs in very poor UMTS or GSM cellular phone coverage. This is totally normal behavior in bad reception areas like in mountains with signal loss.
STEPS TO REPRODUCE
Pre-condition
App is running with active data connection.
Action
iPhone does loss the cellular data connection previously setup. Typically reported as network error code 57.
Observed
The programmed connection.stateUpdateHandler() is called in network connection state '.failed' (OK).
The self-programmed data re-connection includes:
a call to self.connection.cancel()
a call to self.setupUDPConnection() or self.setupConnection() depending on the user settings to re-establish an operative data connection.
However, the iPhone's UMTS/GSM network data (re-)connection state is not properly identified/notified via NWConnection API. There's no further network state notification by means of NWConnection even though the iPhone has recovered a cellular data network.
Expected
The iPhone or any other means automatically reconnects the interrupted data connection on its own. The connection.stateUpdateHandler() is called at time of the device's networking data connection (RF) recovering, subsequently to a connection state failed with error code 57, as the RF module is continuously (independently from the app) for available telephony networks.
QUESTION
How to systematically/properly detect a cellular phone data network reconnection readiness in order to causally reinitialize the NWConnection data connection available used in app.
Relevant code extract
Setup UDP connection (or similarly setup a TCP connection)
func setupUDPConnection() {
let udp = NWProtocolUDP.Options.init()
udp.preferNoChecksum = false
let params = NWParameters.init(dtls: nil, udp: udp)
params.serviceClass = .responsiveData // service type for medium-delay tolerant, elastic and inelastic flow, bursty, and long-lived connections
connection = NWConnection(host: NWEndpoint.Host.name(AppConstant.Web.urlWebSafeSky, nil), port: NWEndpoint.Port(rawValue: AppConstant.Web.urlWebSafeSkyPort)!, using: params)
connection.stateUpdateHandler = { (newState) in
switch (newState) {
case .ready:
//print("UDP Socket State: Ready")
self.receiveUDPConnection(). // data reception works fine until network loss
break
case .setup:
//print("UDP Socket State: Setup")
break
case .cancelled:
//print("UDP Socket State: Cancelled")
break
case .preparing:
//print("UDP Socket State: Preparing")
break
case .waiting(let error):
Logger.logMessage(message: "UDP Connection waiting: "+error.errorCode.description+" \(error.localizedDescription), available Interfaces: \(self.connection.currentPath!.availableInterfaces.description)", LoggerLevels.Error)
break
case .failed(let error):
Logger.logMessage(message: "UDP Connection failed: "+error.errorCode.description+" \(error.localizedDescription), available Interfaces: \(self.connection.currentPath!.availableInterfaces.description)", LoggerLevels.Error)
// data connection retry (expecting network transport layer to be available)
self.reConnectionServer()
break
default:
//print("UDP Socket State: Waiting or Failed")
break
}
self.handleStateChange()
}
connection.start(queue: queue)
}
Handling of network data connection loss
private func reConnectionServer() {
self.connection.cancel()
// Re Init Connection - Give a little time to network recovery
let delayInSec = 30.0. // expecting actually a notification for network data connection availability, instead of a time-triggered retry
self.queue.asyncAfter(deadline: .now() + delayInSec) {
switch NetworkConnectionType {
case 1:
self.setupUDPConnection() // UDP
break
case 2:
self.setupConnection() // TCP
break
default:
break
}
}
}
Does it necessarily require the use of CoreTelephony class CTTelephonyNetworkInfo or class CTCellularData to get notifications of changes to the user’s cellular service provider?
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
Hi, after upgrading to MacOS Sequoia, my connection to my local IP address does not work. The issue is with the PF (MacOS advanced firewall), as I confirmed that my local application works disabling it temporarily.
Does anyone know how can I do to solve this problem? As APP developer, this is a big problem for me.
Thanks in advance.
Hey,
We also opened a feedback assistant request,
and also opened a ticket with Apple Developer Technical Support a while ago that notice the unmount problem also but it was before we pin point the problem to the Network Extension.
After a further investigation, we've found out that the root cause of this problem is cause by having a network filter from the NetworkExtension provider on (Specifically we have tested with the NEFilterDataProvider) while having a Xsan volume.
The NEFilterDataProvider causing problems for the Xsan, and is stalling the shutdown until we get a panic from watchdog timeout, and only then the mac is fully shutdown.
The problem from what we investigated and also talked with you, is that the Xsan process can't unmount the volume and stuck.
We have also noticed that if we install a network extension and allow the popup of the network filters, i.e enabled the NEFilterDataProvider the computer is stuck, and the finder is in a non responsive state until a reboot (Also probably due to the fact the Xsan is now in a problematic state).
This tests was done on latest versions of MacOs 13 & 14.
We have taken a sysdiagnose from the computer while we have tested.
Do you familiar with the problem (We got no answer on the feedback assistant)?
Thank you,
Idan
Hi All,
I am currently working on a Network Extension App for MacOS using 3 types of extensions provided by Apple's Network Extension Framework.
Content Filter, App Proxy (Want to get/capture/log all HTTP/HTTPS traffic), DNS Proxy (Want to get/capture/log all DNS records).
Later parse into human readable format.
Is my selection of network extension types correct for the intended logs I need?
I am able to run with one extension:
Main App(Xcode Target1) <-> Content Filter Extension. Here there is a singleton class IPCConnection between App(ViewController.swift) which is working fine with NEMachServiceName from Info.plist of ContentFilter Extension(Xcode Target2)
However, when I add an App Proxy extension as a new Xcode Target3, I think the App and extension's communication getting messed up and App not getting started/Crashing. Here, In the same Main App, I am adding new separate IPCConnection for this extension.
Here is the project organization/folder structure.
MyNetworkExtension
├──MyNetworkExtension(Xcode Target1)
│ ├── AppDelegate.swift
│ ├── Assets.xcassets
│ ├── Info.plist
│ ├── MyNetworkExtension.entitlement
│ | ── Main
│ |-----ViewController.swift
│ └── Base.lproj
│ └── Main.storyboard
├── ContentFilterExtension(Xcode Target2)
│ ├── ContentFilterExtension.entitlement
│ │ ├── FilterDataProvider.swift
│ │ ├── Info.plist
│ │ ├── IPCConnection.swift
│ │ └── main.swift
├── AppProxyProviderExtension(Xcode Target3)
│ ├── AppProxyProviderExtension.entitlement
│ │ ├── AppProxyIPCConnection.swift
│ │ ├── AppProxyProvider.swift
│ │ ├── Info.plist
│ │ └── main.swift
└── Frameworks
├── libbsm.tbd
└── NetworkExtension.framework
Is my Approach for creating a single Network Extension App with Multiple extensions correct or is there any better approach of project organization that will make future modifications/working easier and makes the maintenance better?
I want to keep the logic for each extension separate while having the same, single Main App that manages everything(installing, activating, managing identifiers, extensions, etc).
What's the best approach to establish a Communication from MainApp to each extension separately, without affecting one another? Is it good idea to establish 3 separate IPC Connections(each is a singleton class) for each extension?
Are there any suggestions you can provide that relates to my use case of capturing all the network traffic logs(including HTTP/HTTPS, DNS Records, etc), especially on App to Extension Communication, where my app unable to keep multiple IPC Connections and maintain them separately?
I've been working on it for a while, and still unable to make the Network Extension App work with multiple extensions(each as a new Xcode target).
Main App with single extension is working fine, but if I add new extension, App getting crashed. I suspect it's due to XPC/IPC connection things!
I really appreciate any support on this either directly or by any suggestions/resources that will help me get better understand and make some progress.
Please reach out if in case any clarifications or specific information that's needed to better understand my questions.
Thank you very much
Topic:
App & System Services
SubTopic:
Networking
Tags:
Frameworks
Network Extension
System Extensions
I have an app with lots of networking calls that are currently done through URLSession. We would like to implement the new carried constrained entitlements and begin moving data through the ultra constrained network path for core features of our application. I have successfully implemented the NWPathMonitor to identify when the current network path is ultra constrained and I have been consistently on a physical device in a real world environment.
I'm aware that we will not be able to use URLSession to do this from other posts in this forum like this one. Because of this problem with URLSession I am attempting to fallback to using NWConnection when the current path is ultra constrained. I have setup a NWConnection with the NWParameters.allowUltraConstrainedPaths set to true. The request works perfectly when connected to wifi or cellular. However, it does not work at all when the current path is ultra constrained. When attempting this request through my NWConnection I receive an error that says:
The operation couldn’t be completed. (Network.NWError error 50 - Network is down)
Is this expected? I have confirmed my physical device is connecting to carrier provided satellite and I have been able to load data in other ios apps from Apple like the music app while on this carrier constrained connection. If this is not the correct way to move data when the path is ultra constrained what is the correct way?
Dear Apple App Store Review Team,
We are currently developing an application focused on user data asset management, aimed at helping users better protect and manage their personal data. One of the core features of our application is to allow users to access files stored on their mobile devices from other devices within the same local network.
At present, our implementation works as follows: once the application is launched, it starts an HTTP service in the background to support access from other devices within the local network.
However, we have encountered a technical challenge in the iOS environment: when the application is moved to the background or the device screen is turned off, the system imposes strict limitations on the runtime of background tasks. Our testing has shown that, typically after about 30 seconds, the background HTTP service is suspended by the system, which prevents other devices from continuing to access the files.
As developers, we would like to clarify the following:
What specific technical steps are required to enable a continuous background HTTP service under iOS?
During development, which aspects (e.g., system permission configurations, App Store review guidelines) need to be addressed to support such functionality?
What qualifications or requirements (e.g., entitlement requests, compliance documentation) are necessary for an application to provide unrestricted HTTP service in the background?
If such behavior is not officially supported, we kindly request that you provide the relevant official guidelines and documentation so that we can fully understand the applicable policies and requirements.
Thank you very much for your time and guidance.
Good morning,
I have been playing with he new Networking framework released in beta, and i think its amazing how powerful and simple it is.
However i have been tackling some issues with it, it seems that the NetworkListener does not allow us to configure a specific endpoint for any of the protocols, UDP, TCP (QUIC, TLS)
Is this intended or just not missing features as of the Beta ?
I figured out how to use bonjour to get a port (as i am brand new to using Networking on macOS and Swift)
I get that the use of this is mainly as a client to connect to servers, but it would make more sense to have a high level abstraction of what already exist, wouldn't it be more intuitive to configure a NetworkEndpoint that contains either a Bonjour Service or an endpoint with configured port that we can then configure on the Listener, instead of doing .service(...) ?
Furuno AP(EW750) is sending EAPOL M1 message, but Iphone16 is not responding with EAPOL M2 message, Hence Iphone16 is unable to connect to Qualcomm based AP with MLO suiteb encryption.
Issue impact: All the Iphone16 users cannot connect to WiFi7 AP with MLO suiteb encryption globally. Predominantly, Iphone users tend to connect to more secured wifi networks using WPA3 suiteb encryption, hence many of the iphone users will experience the connectivity issue significantly.
Topology:
AP Hardware: Furuno WiFi7 AP(EW770) The Furuno WiFi7 AP uses Miami IPQ5332 with waikiki radio QCN9274 (Qualcomm based chipset)
AP software: SPF12.2 CSU3
IPhone16 software: (18.3.1 or 18.5 ) I
phone16 wifi capabilities: 802.11 b/a/g/n/ac/ax/be
Radius server details: Radius server:
Laptop running with Ubuntu Radius package: 3.0.26dfsggit20220223.1.00ed0241fa-0ubuntu3.4 Version: 3.0.26
Steps:
Power on the Wi-Fi 7 Access Point with the Miami chipset, and flash it with the SPF 12.2 CSU3 image.
Enable both 5 GHz and 6 GHz radios on the AP.
Enable MLO (Multi-Link Operation) in 6Ghz & 5Ghz, set MLD address different from radio address and configure Suite-B (192-bit) encryption
On the Linux laptop, set up the RADIUS server with EAP-TLS authentication method.
Once the above steps are completed, take the iPhone 16 and follow the steps below to install the RADIUS client certificates on the device.
On the sniffer laptop, switch the Wi-Fi adapter to monitor mode, configure the required channel, and begin packet capture.
Check SSID is broadcasting, then connect the iPhone 16 to .
Verify if the client (iPhone 16) connects to the SSID using WPA3-Enterprise, MLO, and Suite-B encryption by checking the wireless capture on both the AP and iPhone sides.
Support needed from Apple team: We would request Apple team to analyse and enable the IPhone16 users to connect to advanced security WPA3 Suiteb by resolving the issue.
Below is our analysis and observation for your reference.
As per IEEE, MLD mac address can be set to the same or different from radio address, Iphone16 is not accepting EAPOL M1 message if source address(MLD) is different from radio address.
IPhone16 is accepting EAPOL M1 if the source address(MLD) is set to the same as the radio address and responds with M2 message
IPhone16 is not accepting EAPOL M1 if source address(MLD) set to different from radio address and fails to respond with M2 message.
sysdiagnose.log
log-file
log-file
Please let us know additional logs are required.
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.
NEAppProxyUDPFlow contains below property:
open var localEndpoint: NWEndpoint? { get }
Why is localEndpoint not available for NEAppProxyTCPFlow?
Is there a way to determine the source port of a flow of type NEAppProxyTCPFlow within the following method of NETransparentProxyProvider?
override func handleNewFlow(_ flow: NEAppProxyFlow) -> Bool {
Hi,
I have created an application for NFC tag scanning and read the tag data. For that,
i enabled the capability: NearField Communication Tag reading.
Then I added 2 tag formats in the entitlement
then i added info.plist:
NFCReaderUsageDescription
We need to use NFC
com.apple.developer.nfc.readersession.felica.systemcodes
8005
8008
0003
fe00
90b7
927a
12FC
86a7
com.apple.developer.nfc.readersession.iso7816.select-identifiers
D2760000850100
D2760000850101
but even though when i run the app and tap the nfc card im getting some error:
NFCTag didBecomeActive
2025-08-29 19:08:12.272278+0530 SAFRAN_NFC[894:113090] NFCTag didDetectTags
2025-08-29 19:08:12.282869+0530 SAFRAN_NFC[894:113520] [CoreNFC] -[NFCTagReaderSession _connectTag:error:]:730 Error Domain=NFCError Code=2 "Missing required entitlement" UserInfo={NSLocalizedDescription=Missing required entitlement}
2025-08-29 19:08:12.284044+0530 SAFRAN_NFC[894:113090] NFCTag restarting polling
2025-08-29 19:08:12.372116+0530 SAFRAN_NFC[894:113090] NFCTag didDetectTags
2025-08-29 19:08:12.381535+0530 SAFRAN_NFC[894:113378] [CoreNFC] -[NFCTagReaderSession _connectTag:error:]:730 Error Domain=NFCError Code=2 "Missing required entitlement" UserInfo={NSLocalizedDescription=Missing required entitlement}
2025-08-29 19:08:12.382246+0530 SAFRAN_NFC[894:113090] NFCTag restarting polling
2025-08-29 19:08:12.470667+0530 SAFRAN_NFC[894:113090] NFCTag didDetectTags
2025-08-29 19:08:12.479336+0530 SAFRAN_NFC[894:113378] [CoreNFC] -[NFCTagReaderSession _connectTag:error:]:730 Error Domain=NFCError Code=2 "Missing required entitlement" UserInfo={NSLocalizedDescription=Missing required entitlement}
2025-08-29 19:08:12.480101+0530 SAFRAN_NFC[894:113090] NFCTag restarting polling
Could you please help me wha tis the issue and give solution for that?
Greetings,
I would like to understand this URLCache behavior for two different requests to the same end point but with a different header value. Here is a code with comment explaining the behavior.
// Create a request to for a url.
let url = URL(string: "https://<my url>?f=json")!
var request = URLRequest(url: url)
// Set custom header with a value.
request.setValue("myvalue", forHTTPHeaderField: "CustomField")
// Send request to get the response.
let (data, response) = try await URLSession.shared.data(for: request)
print("data: \(String(describing: String(data: data, encoding: .utf8)))")
print("response: \(response)")
// Create second request to the same url but with different value of custom header field.
var request2 = URLRequest(url: url)
request2.setValue("newvalue", forHTTPHeaderField: "CustomField")
// Check the URL cache for second request and it returns the response
// of the first request even though the second request has different header value.
let cachedResponse = URLCache.shared.cachedResponse(for: request2)
print("cachedResponse: \(cachedResponse?.response)")
Is this a bug in URLCache that request headers are not matched while returning the response?
Is this an expected behavior? If yes, why?
Development environment
Xcode 26.0 Beta 6
iOS 26 Simulator
macOS 15.6.1
To verify TLS 1.3 session resumption behavior in URLSession, I configured URLSessionConfiguration as follows and sent an HTTP GET request:
let config = URLSessionConfiguration.ephemeral
config.tlsMinimumSupportedProtocolVersion = .TLSv13
config.tlsMaximumSupportedProtocolVersion = .TLSv13
config.httpMaximumConnectionsPerHost = 1
config.httpAdditionalHeaders = ["Connection": "close"]
config.enablesEarlyData = true
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let url = URL(string: "https://www.google.com")!
var request = URLRequest(url: url)
request.assumesHTTP3Capable = true
request.httpMethod = "GET"
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("Error during URLSession data task: \(error)")
return
}
if let data = data, let responseString = String(data: data, encoding: .utf8) {
print("Received data via URLSession: \(responseString)")
} else {
print("No data received or data is not UTF-8 encoded")
}
}
task.resume()
However, after capturing the packets, I found that the ClientHello packet did not include the early_data extension.
It seems that enablesEarlyData on URLSessionConfiguration is not being applied.
How can I make this work properly?
Hello Apple Developer Community,
We are developing a full-tunnel VPN app for macOS that utilizes a packet tunnel network system extension (via NEPacketTunnelProvider). We're committed to using a system extension for this purpose, as it aligns with our requirements for system-wide tunneling. The app is sandboxed and intended for distribution on the Mac App Store.
Here's the workflow:
The app (running in user context) downloads a VPN profile from our server.
It generates private keys, appends them to the profile, and attempts to save this enhanced profile securely in the keychain.
The packet tunnel system extension (running in root context) needs to access this profile, including the private keys, to establish the VPN connection.
We've encountered challenges in securely sharing this data across the user-root boundary due to sandbox restrictions and keychain access limitations. Here's what we've tried so far, along with the issues:
Writing from the App to the System Keychain:
Attempted to store the profile in the system keychain for root access. This fails because the sandboxed app lacks permissions to write to the system keychain. (We're avoiding non-sandboxed approaches for App Store compliance.)
Extension Reading Directly from the User Login Keychain:
Tried having the extension access the user's login keychain by its path.
We manually added the network extension (located in /Library/SystemExtensions//bundle.systemextension) to the keychain item's Access Control List (ACL) via Keychain Access.app for testing.
This results in "item not found" errors, likely due to the root context not seamlessly accessing user-keychain items without additional setup.
Using Persistent References in NETunnelProviderProtocol:
The app stores the profile in the user keychain and saves a persistent reference (as Data) in the NETunnelProviderProtocol's identityReference or similar fields. The extension then attempts to retrieve the item using this reference.
We manually added the network extension (located in /Library/SystemExtensions//bundle.systemextension) to the keychain item's Access Control List (ACL) via Keychain Access.app for testing.
However, this leads to error -25308 (errSecInteractionNotAllowed) when the extension tries to access it, possibly because of the root-user context mismatch or interaction requirements.
Programmatically Adding the Extension to the ACL:
Explored using SecAccess and SecACL APIs to add the extension as a trusted application. This requires SecTrustedApplicationCreateFromPath to create a SecTrustedApplicationRef from the extension's path.
Issue 1: The sandboxed app can't reliably obtain the installed extension's path (e.g., via scanning /Library/SystemExtensions or systemextensionsctl), as sandbox restrictions block access.
Issue 2: SecTrustedApplicationCreateFromPath is deprecated since macOS 10.15, and we're hesitant to rely on it for future compatibility.
We've reviewed documentation on keychain sharing, access groups (including com.apple.managed.vpn.shared, but we're not using managed profiles/MDM) as the profiles are download from a server, and alternatives like XPC for on-demand communication, but we're unsure if XPC is suitable for sensitive data like private keys during tunnel creation. And if this is recommended what is going to be the approach here.
What is the recommended, modern approach for this scenario? Is there a non-deprecated way to handle ACLs or share persistent references across contexts? Should we pursue a special entitlement for a custom access group, or is there a better pattern using NetworkExtension APIs?
Any insights, code snippets, or references to similar implementations would be greatly appreciated. We're targeting macOS 15+.
Thanks in advance!
Hello,
I've been experimenting with the new NEURLFilter API and so far the results are kind of strange.
SimpleURLFilter sample contains a bloom filter that seems to be built from this dataset in pir-service-example.
I was able to run SimpleURLFilter sample and configure it to use PIRService from the example repo. I also observed the requests that iOS has been sending: requesting config and then sending /queries request.
What I haven't seen is any .deny verdict for any URL. Even when calling NEURLFilter.verdict(for: url) directly I cannot see a .deny verdict.
Is there anything wrong with the sample or is there a known issue with NEURLFilter in the current beta (beta 8) that prevents it from working?
We currently supporting proxy app with Tunnel.appEx and PacketTunnelProvider.
Some users report about constant error "The VPN session failed because an internal error occurred." on VPN start (which fails rapidly).
This error occur mostly after user updated app with active VPN.
Rebooting device solves the problem and it doesnt come again, but it is still very frustrating.
I can provide any required info about app setup to solve this issue if you need. Thanks
There are multiple report of crashes on URLConnectionLoader::loadWithWhatToDo. The crashed thread in the stack traces pointing to calls inside CFNetwork which seems to be internal library in iOS.
The crash has happened quite a while already (but we cannot detect when the crash started to occur) and impacted multiple iOS versions recorded from iOS 15.4 to 18.4.1 that was recorded in Xcode crash report organizer so far.
Unfortunately, we have no idea on how to reproduce it yet but the crash keeps on increasing and affect more on iOS 18 users (which makes sense because many people updated their iOS to the newer version) and we haven’t found any clue on what actually happened and how to fix it on the crash reports. What we understand is it seems to come from a network request that happened to trigger the crash but we need more information on what (condition) actually cause it and how to solve it.
Hereby, I attach sample crash report for both iOS 15 and 18.
I also have submitted a report (that include more crash reports) with number: FB17775979.
Will appreciate any insight regarding this issue and any resolution that we can do to avoid it.
iOS 15.crash
iOS 18.crash
Hi,
We’re seeing our build system (Gradle) get stuck in sendto system calls while trying to communicate with other processes via the local interface over UDP. To the end user it appears that the build is stuck or they will receive an error “Timeout waiting to lock XXX. It is currently in use by another Gradle instance”. But when the process is sampled/profiled, we can see one of the threads is stuck in a sendto system call. The only way to resolve the issue is to kill -s KILL <pid> the stuck Gradle process.
A part of the JVM level stack trace:
"jar transforms Thread 12" #90 prio=5 os_prio=31 cpu=0.85ms elapsed=1257.67s tid=0x000000012e6cd400 nid=0x10f03 runnable [0x0000000332f0d000]
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.DatagramChannelImpl.send0(java.base@17.0.10/Native Method)
at sun.nio.ch.DatagramChannelImpl.sendFromNativeBuffer(java.base@17.0.10/DatagramChannelImpl.java:901)
at sun.nio.ch.DatagramChannelImpl.send(java.base@17.0.10/DatagramChannelImpl.java:863)
at sun.nio.ch.DatagramChannelImpl.send(java.base@17.0.10/DatagramChannelImpl.java:821)
at sun.nio.ch.DatagramChannelImpl.blockingSend(java.base@17.0.10/DatagramChannelImpl.java:853)
at sun.nio.ch.DatagramSocketAdaptor.send(java.base@17.0.10/DatagramSocketAdaptor.java:218)
at java.net.DatagramSocket.send(java.base@17.0.10/DatagramSocket.java:664)
at org.gradle.cache.internal.locklistener.FileLockCommunicator.pingOwner(FileLockCommunicator.java:61)
at org.gradle.cache.internal.locklistener.DefaultFileLockContentionHandler.maybePingOwner(DefaultFileLockContentionHandler.java:203)
at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock$1.run(DefaultFileLockManager.java:380)
at org.gradle.internal.io.ExponentialBackoff.retryUntil(ExponentialBackoff.java:72)
at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.lockStateRegion(DefaultFileLockManager.java:362)
at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.lock(DefaultFileLockManager.java:293)
at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.<init>(DefaultFileLockManager.java:164)
at org.gradle.cache.internal.DefaultFileLockManager.lock(DefaultFileLockManager.java:110)
at org.gradle.cache.internal.LockOnDemandCrossProcessCacheAccess.incrementLockCount(LockOnDemandCrossProcessCacheAccess.java:106)
at org.gradle.cache.internal.LockOnDemandCrossProcessCacheAccess.acquireFileLock(LockOnDemandCrossProcessCacheAccess.java:168)
at org.gradle.cache.internal.CrossProcessSynchronizingCache.put(CrossProcessSynchronizingCache.java:57)
at org.gradle.api.internal.changedetection.state.DefaultFileAccessTimeJournal.setLastAccessTime(DefaultFileAccessTimeJournal.java:85)
at org.gradle.internal.file.impl.SingleDepthFileAccessTracker.markAccessed(SingleDepthFileAccessTracker.java:51)
at org.gradle.internal.classpath.DefaultCachedClasspathTransformer.markAccessed(DefaultCachedClasspathTransformer.java:209)
at org.gradle.internal.classpath.DefaultCachedClasspathTransformer.transformFile(DefaultCachedClasspathTransformer.java:194)
at org.gradle.internal.classpath.DefaultCachedClasspathTransformer.lambda$cachedFile$6(DefaultCachedClasspathTransformer.java:186)
at org.gradle.internal.classpath.DefaultCachedClasspathTransformer$$Lambda$368/0x0000007001393a78.call(Unknown Source)
at org.gradle.internal.UncheckedException.unchecked(UncheckedException.java:74)
at org.gradle.internal.classpath.DefaultCachedClasspathTransformer.lambda$transformAll$8(DefaultCachedClasspathTransformer.java:233)
at org.gradle.internal.classpath.DefaultCachedClasspathTransformer$$Lambda$372/0x0000007001398470.call(Unknown Source)
at java.util.concurrent.FutureTask.run(java.base@17.0.10/FutureTask.java:264)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(java.base@17.0.10/ThreadPoolExecutor.java:1136)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(java.base@17.0.10/ThreadPoolExecutor.java:635)
at java.lang.Thread.run(java.base@17.0.10/Thread.java:840)
A part of the process sample:
2097 Thread_3879661: Java: jar transforms Thread 12
+ 2097 thread_start (in libsystem_pthread.dylib) + 8 [0x18c42eb80]
...removed for brevity...
+ 2097 Java_sun_nio_ch_DatagramChannelImpl_send0 (in libnio.dylib) + 84 [0x102ef371c]
+ 2097 __sendto (in libsystem_kernel.dylib) + 8 [0x18c3f612c]
We have observed the following system logs around the time the issue manifests:
2025-08-26 22:03:23.280255+0100 0x3b2c00 Default 0x0 0 0 kernel: cfil_hash_entry_log:6088 <CFIL: Error: sosend_reinject() failed>: [4628 java] <UDP(17) in so 9e934ceda1c13379 50826943645358435 50826943645358435 ag>
2025-08-26 22:03:23.280267+0100 0x3b2c00 Default 0x0 0 0 kernel: cfil_service_inject_queue:4472 CFIL: sosend() failed 22
The issue seems to be rooted in the built-in Application Firewall, as disabling it “fixes” the issue. It doesn’t seem to matter that the process is on the “allow” list.
We’re using Gradle 7.6.4, 8.0.2 and 8.14.1 in various repositories, so the version doesn’t seem to matter, neither does which repo we use.
The most reliable way to reproduce is to run two Gradle builds at the same time or very quickly after each other.
We would really appreciate a fix for this as it really negatively affects the developer experience. I've raised FB19916240 for this.
Many thanks,
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"
It's not yet fully clear why and when does this crash occur, but I'm creating this post so there's a centralized thread for this.
Some hints collected so far:
The crash is occurring for existing Xcode projects opened with new Xcode 26.0 beta (17A5241e); no one's been able to reproduce on a project created in Xcode 26. I even tried creating a project with Xcode 16.2 and open it in Xcode 26, but it's all working fine there (don't have older Xcode at the moment, to try with many versions)
It crashes right at the line of code that initializes URLSessionConfiguration. If you call URLSession() without parameters (which is deprecated as of iOS 13), the session initializes without the crash.
It's NOT occurring only for libraries installed through package manages. In a project where it crashes, one should be able to reproduce by adding URLSessionConfiguration.default as the first line in didFinishLaunchingWithOptions
It crashes when running an app on an iOS 26 simulator. (I don't have a device running beta iOS 26 to test on it!) It's working fine when running the app on a simulator or a device running iOS 18 or older.
Related issue on Firebase GitHub repo: https://github.com/firebase/firebase-ios-sdk/issues/14948
Sorry to not be able to provide more info at the moment. I wanted to report this so in case someone from Apple knows about it, we could at least get some feedback or workarounds, until fix is released -- and, to prevent us all from duplicating this report in repositories of each library, as this isn't related to libraries.