The Download is not Working in the background mode even if i entitled all the necessary permission for the application it only works when the app is connected to xcode due to xcode keep the session alive but if try after removing the connection from the xcode the app not able to keep the download after 45 sec what may be the reason
my code
var request = URLRequest(url: url)
request.httpMethod = "GET"
let bearerToken = SyncManager.accessToken
request.setValue("Bearer \(bearerToken)", forHTTPHeaderField: "Authorization")
let uniqueIdentifier = "\(self.vdmsId)_\(UUID().uuidString)"
backgroundTaskID = UIApplication.shared.beginBackgroundTask { [weak self] in
if let taskID = self?.backgroundTaskID {
UIApplication.shared.endBackgroundTask(taskID)
self?.backgroundTaskID = .invalid
}
}
let CursessionConfig = URLSessionConfiguration.background(withIdentifier: uniqueIdentifier)
CursessionConfig.isDiscretionary = false
CursessionConfig.sessionSendsLaunchEvents = true
CursessionConfig.shouldUseExtendedBackgroundIdleMode = true
// Set timeout intervals
CursessionConfig.timeoutIntervalForResource = 24 * 60 * 60 // 24 hours
CursessionConfig.timeoutIntervalForRequest = 60 * 60 // 1 hour
let Cursession = URLSession(configuration: CursessionConfig, delegate: self, delegateQueue: nil)
self.CurInstanceSession = Cursession
self.session = Cursession
if SyncManager.activeSessions == nil {
SyncManager.activeSessions = [URLSession]()
}
SyncManager.activeSessions?.append(Cursession)
self.downloadCompletionHandler = completion
let CurdownloadTask = Cursession.downloadTask(with: request)
CurdownloadTask.resume()
is there any solutions and i have entitled all the neccessary permisssions like background fetch, process and i also tries with the UIApplication.shared.beginBackgroundTask but after 45 sec it gets terminated all of the suden what may be the issue
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.
Post
Replies
Boosts
Views
Activity
Hi,
I have been reviewing some previous discussions around networking in macOS, and I’d like to clarify my understanding of the differences between the kernel-space network stack and user-space network stack and validate this understanding based on the information shared in earlier threads.
I’m also curious about how these differences impact macOS applications, particularly those requiring maintaining many simultaneous network connections.
Understanding Kernel-Space vs User-Space Network Stack
Kernel-Space Network Stack (BSD Sockets):
The kernel-space networking stack refers to the traditional networking layer that runs in the kernel and handles network communication via BSD sockets. This stack is lower-level and interacts directly with the operating system's networking drivers and hardware. All network connections managed through this stack require a socket (essentially a file descriptor) to be opened, which places limits on the number of file descriptors that can be used (for example, the default 64K limit for sockets). The kernel network stack is traditionally used on macOS (and other UNIX-based systems) for networking tasks, such as when you use system APIs like BSD sockets.
User-Space Network Stack (Network Framework): The user-space network stack in macOS (via the Network framework) allows applications to handle networking tasks without directly using the kernel. This provides more flexibility and performance benefits for certain types of network operations, as the networking stack is managed in user space rather than kernel space. This approach reduces overhead and allows more control over networking configurations. In theory, with user-space networking, the application wouldn't be bound by kernel-level socket limits, and it could handle many more simultaneous connections efficiently.
In previous posts on that thread, Quinn mentioned that the Network framework in macOS can rely on the user-space stack (by default) for network operations, but there are still cases where macOS falls back to using the kernel stack (i.e., BSD sockets) under certain conditions. One key example is when the built-in firewall is enabled. This prevents user-space networking from functioning as expected, and the system defaults to using the kernel's BSD sockets for network communication.
In the same discussion, it was also highlighted that NECP (Network Extension Control Plane) could place further limitations on user-space networking, and eventually, systems may run into issues like ENOSPC errors due to excessive simultaneous network flows. This suggests that while user-space networking can offer more flexibility, it's not immune to limits imposed by other system resources or configurations.
Given the information above, I wanted to confirm:
Is the above understanding correct and does the macOS Network framework still use the user-space networking stack in macOS 14 and beyond?
Under what conditions would the system fall back to using the kernel stack (BSD sockets) instead of the user-space stack? For example, does enabling the firewall still disable user-space networking?
What is the practical impact of this fallback on applications that require many simultaneous network connections? Specifically, are there any limitations like the 64K socket limit that developers should be aware of when the system uses the user space stack, and what are the best practices to manage large numbers of connections?
I have an issue that causes multiple instances of the push provider to be initialized. And I'd like to ask you what could trigger the instantiation NEAppPushProvider subclass. It seems like it's being triggered excessively. If there's documentation that I have overlooked then just show it to me and I'll be on my way.
Here's the details. But really all I want to know is why is my subclass for NEAppPushProvider keeps getting initialized. If you can answer me that than maybe all these details don't really matter but here they are.
Here's why I believe there's multiple push provider. I see logs for my push provider initializing but I don't see it de-initializing. I also see redundant logs showing multiple instances trying to log into my server. Each time it initializes, an additional log is added for trying to log into my server.
In the app, the system saves it's configuration shortly after initialization, after saving and loading the push configuration, the app doesn't touch config.
Meanwhile in the extension, after 8 or so hours, the extension starts creating a new instance of the push provider. Then a few hours later it does it again. And again. Until the watch dog kills us for wasting too much CPU.
Normally on a fresh install, I'll observe turning off the wifi to call stop on the push provider and later have the push provider de-initialize.
The extension maintains a socket connection to the server, the server can send it messages to display push notifications. The software runs on hospital networks, which will not have access to the internet. It seems like the connection to the server is stable from the logs. I don't detect any disconnections. I'll check with the server to confirm.
In the app I call removeFromPreferences to clear out any extensions before logging in/saving push configurations. And I call saveToPreferences on the NEAppPushManager. I do this to make sure I don't have more than one push configuration saved at one time. I also have many logs looking out for this. I used the sample code from apple as the basis of the my own Push Manager. I can post code if you deem it necessary.
Hope to here from you soon. Thank you.
I added a Content Filter to my app, and when running it in Xcode (Debug/Release), I get the expected permission prompt:
"Would like to filter network content (Allow / Don't Allow)".
However, when I install the app via TestFlight, this prompt doesn’t appear at all, and the feature doesn’t work.
Is there a special configuration required for TestFlight? Has anyone encountered this issue before?
Thanks!
In our iOS networking related app for the app store (with network extension using packet tunnel provider), we are supposed to read the list of nameservers for the network. We use res_ninit function.
This function returns only 3 items (but in reality the network has more dns servers. In my case 5. Some ipv4 and some ipv6)
Looking at the header file at iOS 18.2 -> user/include/resolve.h, it shows that the __res_state struct has a maximum limit of 3 for the nsaddr_list array.
It seems that the reason the res_ninit function returns only 3 values is because of this. For our code to work correctly, it needs to know all the dns servers, but we only get partial results.
Is there any other api that can get us all the dns servers ?
I am unable to apply for Multicast Entitlement at https://developer.apple.com/contact/request/networking-multicast
The reason for this is unclear. I have paid for a developer account and believe I'm up to date with all agreements.
Hi all,
I’m developing a watchOS app that uses a WebSocket API to process voice audio. However, I keep encountering this error when trying to establish the connection:
nw_endpoint_flow_failed_with_error [C1 <server URL>:443 failed parent-flow (unsatisfied (Path was denied by NECP policy), interface: ipsec2, ipv4, ipv6, proxy)] already failing, returning
I’ve read Technical Note TN3135, which outlines an exception for audio streaming apps. My app is an audio streaming app, and I’ve already added background audio mode to the app’s capabilities. However, I’m not sure what else is required to meet the exception described in TN3135.
Questions
How do I meet the exception outlined in TN3135 for WebSocket audio streaming on watchOS?
Does NECP enforce additional restrictions even with background audio enabled, and how can I address this?
Any guidance or examples of implementing WebSocket audio streaming on watchOS would be greatly appreciated.
Thanks!
Hi everyone,
I’m working with the DNSServiceGetAddrInfo API and came across the following statement in the documentation:
If the call succeeds then it initializes the DNSServiceRef, returns kDNSServiceErr_NoError, and the query begins and will last indefinitely until the client terminates the query by passing this DNSServiceRef to DNSServiceRefDeallocate(_)
I’m trying to understand exactly what this means in practice. Specifically, after receiving a response with kDNSServiceFlagsMoreComing, being set to 0 does it imply that the OS itself continues querying the DNS periodically or indefinitely, even after we've already received some results? Or does it only continue fetching additional results related to the initial query until we explicitly terminate it?
Any clarification on the behavior of this query would be greatly appreciated!
Thanks in advance!
Hello, we have noticed a crash in BigSur 11.7.10, 20G1427 libdispatch:
Crashed Thread: 1 Dispatch queue: com.apple.network.connections
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Signal: Illegal instruction: 4
Termination Reason: Namespace SIGNAL, Code 0x4
Terminating Process: exc handler [94088]
Application Specific Information:
BUG IN CLIENT OF LIBDISPATCH: Release of a suspended object
Thread 0:
0 libsystem_kernel.dylib 0x00007fff20488aea __sigsuspend_nocancel + 10
1 libdispatch.dylib 0x00007fff2031f4e1 _dispatch_sigsuspend + 36
2 libdispatch.dylib 0x00007fff2031f4bd _dispatch_sig_thread + 53
Thread 1 Crashed:: Dispatch queue: com.apple.network.connections
0 libdispatch.dylib 0x00007fff2033cc35 _dispatch_queue_xref_dispose.cold.1 + 24
1 libdispatch.dylib 0x00007fff20313808 _dispatch_queue_xref_dispose + 50
2 libdispatch.dylib 0x00007fff2030e2eb -[OS_dispatch_source _xref_dispose] + 17
3 libnetwork.dylib 0x00007fff24255999 __nw_queue_context_create_source_block_invoke + 41
4 libdispatch.dylib 0x00007fff2030d623 _dispatch_call_block_and_release + 12
5 libdispatch.dylib 0x00007fff2030e806 _dispatch_client_callout + 8
6 libdispatch.dylib 0x00007fff203111b0 _dispatch_continuation_pop + 423
7 libdispatch.dylib 0x00007fff203211f4 _dispatch_source_invoke + 1181
8 libdispatch.dylib 0x00007fff20316318 _dispatch_workloop_invoke + 1784
9 libdispatch.dylib 0x00007fff2031ec0d _dispatch_workloop_worker_thread + 811
10 libsystem_pthread.dylib 0x00007fff204b545d _pthread_wqthread + 314
11 libsystem_pthread.dylib 0x00007fff204b442f start_wqthread + 15
I have seen similar crashes in the forum, but none from com.apple.network.connections queue.
Should we raise a ticket or is this something that was fixed in newer OS versions?
Thanks!
Jakub
Context: We are using NWConnection for UDP and TCP Connections, and wanted to know the best way to keep the number of pending send completions in control to limit resource usage
Questions:
Is there a way to control the send rate, such that too many 'send pending completion' does not get queued. Say if I do a ‘extremely dense flurry of 10 million NWConnection.send’ will all go asynchronous without any complications? Or I would be informed once it reaches some threshold.
Or no? And is it the responsibility of the application using NWConnection.send to limit the outstanding completion , as if they were beyond a certain limit, it would have an impact on outstanding and subsequent requests?
If so – how would one know ‘what is supposed to be the limit’ at runtime? Is this a process level or system level limit.
Will errors like EAGAIN and ETIMEOUT ever will be reported. In the test I simulated, where the TCP Server was made to not do receive, causing the 'socket send buffer' to become full on the sender side. On the sender side my send stopped getting complete, and became pending. Millions of sends were pending for long duration, hence wanted to know if we will ever get EAGAIN or ETIMEOUT.
I've implemented a custom system extension VPN for macOS using Packet Tunnel Provider.
The VPN is configured with on-demand, and a rule to always connect whenever there's traffic:
onDemandRules = [NEOnDemandRuleConnect()]
As for the tunnel's settings (at the Packet Tunnel Provider), I've configured a split tunnel, so some routes are excluded from the tunnel.
Now I have the following scenario:
The VPN is connected
The Mac enters sleep
The sleep() function is called (at my Packet Tunnel Provider)
The Mac briefly awakes to check emails/push notifications/etc. This traffic is excluded from the tunnel.
What is the expected behavior here? Should the wake function be called because of the on-demand rule? Or should the VPN remain asleep because this traffic is excluded from the tunnel?
Hi,
I would like to confirm if the matchDomains property in NERelayManager operates exclusively at the application layer. Specifically, it seems that adding IPv4 addresses or IPv4 CIDR blocks to the matchDomains list does not work, as the relay manager appears unable to match them.
Relay Configuration
For example, I tried adding the following IPv4 patterns to the matchDomains list:
11.22.33.44
11.22..
11.22.*
In this configuration, I expected traffic to be routed to the relay server as defined by the matchDomains entries. However, the relay manager did not handle these IPv4 patterns as anticipated.
On the other hand, when using only the excludedDomains property, the desired IPv4 traffic is successfully routed to the relay server as expected.
Purpose of Forwarding IPv4 to the Relay Server
The primary reason for forwarding IPv4 traffic to the relay server is to address cases where certain applications—such as those developed with Flutter or React Native—use their own custom network stack. These custom network stacks often do not respect the relay configuration. As a result, even when these applications use domains that are matched by the relay manager’s matchDomains, their TCP connections to DNS-resolved IPv4 addresses bypass the relay server and connect directly to the IPv4 server.
This behavior makes it critical to enable IPv4 matching to ensure all traffic, regardless of the application’s network stack implementation, is routed through the relay server.
Questions
Can IPv4 addresses or IPv4 CIDR blocks be used with matchDomains?
If not, is there an alternative method to enable IPv4 matching while keeping matchDomains enabled?
Thank you for your assistance.
Hi,
I would like to confirm whether the matchDomains property in NERelayManager operates strictly at the Application Layer. Specifically, it seems that adding IPv4 addresses or IPv4 CIDR blocks to the matchDomains list does not work, as the relay manager appears unable to match them.
For example, I tried adding the following IPv4 patterns to the matchDomains list:
11.22.33.44
11.22..
11.22.*
However, these IPv4 addresses or patterns are not routed through my Relay server.
Additionally, I have observed that when using only the excludedDomains property, the desired IPv4 traffic is correctly routed to the relay server as expected.
My question is: Can IPv4 addresses or IPv4 CIDR ranges work with matchDomains? If not, is there an alternative approach to enable IPv4 matching while matchDomains is active?
We're seeing some new and odd behavior where our NEPacketTunnelProvider instance is receiving a stopTunnelWithReason:completionHandler: call with reason NEProviderStopReasonInternalError.
Can anyone shed some light into how to diagnose this situation?
Here are some basic details:
Our PacketTunnel has been in use for years and we only started seeing this issue recently.
We're able to reproduce this behavior with some light browsing.
The documentation provides no insight on why/when this might occur. Can anyone shed some light into how to diagnose this situation?
Things we’ve tried so far:
We grabbed a sysdiagnose and looked through the logs:
a. Right before the stopTunnel, we see log items referring to a "nesessionmanager" (PID 2038) getting killed. Presumably, this is due to hitting a highwater threshold. (See sysdiagnose items listing below)
b. Thinking these were due to memory pressure, we added logging of available/used memory.
c. We confirmed that the PacketTunnel was only using 11,808.73 KB.
d. Since, there is plenty of memory available the PacketTunnel was not killed for using too much memeory.
We wondered if this could be due to our UI's usage of objects like: NETunnelProviderManager and NETunnelProviderSession
a. We ran an experiment where we swiped closed the UI to ensure these manager/session objects are not used.
b. Without the UI, we still saw the random stopTunnel with NEProviderStopReasonInternalError.
We wondered if our routes were the problem, but they seem correct.
a. See the NEPacketTunnelNetworkSettings listing below
LISTING: From the system_logs.logarchive, the nesessionmanager log items:
2025-01-23 15:07:59.176146 -0800 0x278 memorystatus com.apple.xnu memorystatus: killing process 2038 [nesessionmanager] in high band ? (140) - memorystatus_available_pages: 18932 default kernel
2025-01-23 15:07:59.179641 -0800 0x278 memorystatus com.apple.xnu memorystatus: killing_highwater_process pid 2038 [nesessionmanager] (highwater 140) 7056KB - memorystatus_available_pages: 19161 compressor_size:69593 default kernel
2025-01-23 15:07:59.179888 -0800 0x278 memorystatus com.apple.xnu memorystatus: failed to kill a process and no memory was reclaimed default kernel
2025-01-23 15:07:59.185695 -0800 1 0x45e0c user/501/com.apple.nesessionmanager [2038] exited with exit reason (namespace: 1 code: 0x2) - JETSAM_REASON_MEMORY_HIGHWATER, ran for 266329ms default launchd
2025-01-23 15:07:59.231188 -0800 31 0x45bf2 com.apple.networkextension nesessionmanager(2038) exited default UserEventAgent
2025-01-23 15:07:59.253371 -0800 31 0x45bf2 com.apple.networkextension nesessionmanager exited with active sessions, re-launching nesessionmanager to clear agent status default UserEventAgent
LISTING: From the system_logs.logarchive, the stopTunnel from PID 2046
2025-01-23 15:07:59.201581 -0800 SamplePacketTunnel [Extension com.REDACTED.PacketTunnel]: Calling stopTunnelWithReason because: None
2025-01-23 15:08:20.783112 -0800 SamplePacketTunnel 2025-01-23 15:08:20,786 2046 ERROR REDACTED (285805) - Exiting after waiting for stopTunnelWithReason
LISTING: routes from NEPacketTunnelNetworkSettings
{
tunnelRemoteAddress = fd12:3456:789a:1::1
DNSSettings = {
protocol = cleartext
server = (
2606:4700:4700::1234,
2606:4700:4700::2345,
)
matchDomains = (
,
)
matchDomainsNoSearch = NO
}
IPv6Settings = {
configMethod = manual
addresses = (
fd12:3456:789a:1::1,
)
networkPrefixLengths = (
64,
)
includedRoutes = (
{
destinationAddress = 2606:4700:4700::2345
destinationNetworkPrefixLength = 128
},
{
destinationAddress = 2606:4700:4700::1234
destinationNetworkPrefixLength = 128
},
)
excludedRoutes = (
{
destinationAddress = REDACTED
destinationNetworkPrefixLength = 128
},
{
destinationAddress = REDACTED
destinationNetworkPrefixLength = 128
},
)
}
MTU = 3072
}
Thanks for taking a look, any help or suggestions would be greatly appreciated
We've been directed here by Quinn in DTS.
We use multicast/broadcast messages extensively in our physical products for discovery purposes. If, for whatever reason, our customers cannot get this to work on their home Wi-Fi network, we advise that they connect to an iPhone hotspot to confirm behaviour and perform firmware updates as needed.
As of iOS 18, we're seeing odd behaviour when using Personal Hotspot. Interestingly, we're also seeing that client devices connected to the Hotspot network are not showing a Subnet Mask in the Wi-Fi Details screen in the iOS Settings app - I don't know if that's related. We're also seeing that screen show an IP address of 192.0.0.2 for all client iPhones connected to an iPhone Hotspot.
Getting more specific, we're seeing that multicast messages are no longer being received by clients when connected to an iPhone Hotspot where the iPhone running the hotspot is running iOS 18.0 or newer. By "multicast", I mean we're using a BSD socket to send data to 255.255.255.255
I've confirmed that our app has the multicast entitlement, the user has granted Local Network permission, and we've created a small sample app that demonstrates this behaviour perfectly - when connected to any other test network, multicast messages are received correctly by clients.
We've also confirmed that this behaviour doesn't happen when the iPhone running the hotspot is running older iOS versions. We've tried a number of iOS 17.x releases and a number of iOS 16.x releases specifically with our sample app, but have been using this exact code since our app's original iOS 9 deployment target and have had no issues until now.
We are trying to connect an accessory to the home's Wi-Fi network and we want to pass that name from the app to the accessory. Passing via Bluetooth.
Is there and API available on iOS to list the networks that the phone can see?
We recently notified from Apple that our Hotspot helper is delaying device to switch Wifi Networks. To handle this issue better, we need to refactor our code a bit handle the scenario gracefully and while reading this documentation https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/Hotspot_Network_Subsystem_Guide/Contents/AuthStateMachine.html#//apple_ref/doc/uid/TP40016639-CH2-SW1
Some questions came up while responding back to evaluate and filterscanlist command. Here are our questions
What is the lifecycle of exclude_list? Does it get cleared every time Authentication State Machine goes into Inactive State?
What happens if we send commandNotRecognized/unsupportedNetwork/temporaryFailure after evaluate command? Does our app get an evaluate command next time when device joins the same network?
What is the actual time for the app to respond to network change evaluate command? Is 45 seconds the timeout limit for app to evaluate and respond?
After responding to the evaluate command, how quickly is it terminated from running in the background?
We’ve been dealing with local network permission issues on macOS 15. Although 15.1 brought some improvement, users are now reporting similar problems again on 15.2.
Our setup:
A “launcher” app (installed from a web package, not sandboxed) uses NSTask to launch our main macOS app.
This macOS app connects to an iOS app via the local network.
We expect a local network permission prompt to appear when the new app launches, but for many users, it never does.
In cases where it worked on an earlier macOS version, there’s no entry in System Settings > Privacy & Security > Local Network, so they can’t toggle anything.
Oddly, if we run the macOS app directly in 15.2, local network access works, yet the privacy entry is still sometimes missing.
We haven’t found a clear way to troubleshoot this within the current API. Has anyone experienced a similar issue, or have suggestions on how to debug and resolve this? Thanks in advance!
I’m working with the NEHotspotHelper API in my iOS app, and I noticed the following log message in Console:
"(BUNDLE ID ) is using NEHotspotHelper API and it's unresponsive to API's evaluate command. The API gives 45 seconds to 3rd party apps to respond, and then it launches WebSheet to allow user to interact with the portal."
I have two different apps that both register a NEHotspotHelper handler:
App A checks for .evaluate and calls createResponse(.unsupportedNetwork) if we don’t manage that particular network.
App B registers for hotspot events but does not handle .evaluate at all.
In App A, whenever I see that “unresponsive” or “45 seconds” log, the system eventually launches the standard captive portal WebSheet. In App B, I never see those logs.
I have a few questions:
Are these “unresponsive” logs indeed triggered by the .evaluate command specifically?
In other words, do we only see that 45-second timeout and the subsequent WebSheet message if our app is registered to handle Evaluate but doesn’t respond quickly (or responds with .unsupportedNetwork)?
Is it best practice (or required) to always respond to .evaluate—for example, sending .unsupportedNetwork if we don’t plan on managing the user’s login or captive portal? Does ignoring .evaluate lead to other unexpected behavior or logs?
Should we still explicitly respond to Evaluate with .unsupportedNetwork? Or is it okay to skip Evaluate handling entirely on every app or invocation?
I’d love to confirm whether .evaluate handling is the direct cause of these logs, and how best to avoid the “unresponsive”/“45 seconds” fallback if our app isn’t intended to manage the portal.
Thanks in advance for any insights!
During development, before things eventually go live, if the associated server for a message filter extension has a self signed SSL then if/how can test iPhones be configured such that the OS will connect to the server when they are performing a message filter query request?