CFNetwork

RSS for tag

Access network services and handle changes in network configurations using CFNetwork.

Posts under CFNetwork tag

65 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Networking Resources
General: DevForums 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 DevForums post Choosing a Network Debugging Tool documentation WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi? TN3135 Low-level networking on watchOS TN3179 Understanding local network privacy Adapt to changing network conditions tech talk Extra-ordinary Networking DevForums post Foundation networking: DevForums tags: Foundation, CFNetwork URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms. Network framework: DevForums tag: Network Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms. 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 DevForums 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: DevForums tag: Core WLAN Core WLAN framework documentation Wi-Fi Fundamentals Secure networking: DevForums tags: Security Apple Platform Security support document Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS). Available trusted root certificates for Apple operating systems support article Requirements for trusted certificates in iOS 13 and macOS 10.15 support article About upcoming limits on trusted certificates support article Apple’s Certificate Transparency policy support article 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 DevForums tags: 5G, QUIC, Bonjour On FTP DevForums post Using the Multicast Networking Additional Capability DevForums post Investigating Network Latency Problems DevForums post WirelessInsights framework documentation iOS Network ****** Strength Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
3.2k
5d
How to manage tmp/CFNetworkDownload_*.tmp files from URLSessionDownloadTask on network failure?
Question: What is the standard, most reliable way to manage temporary files associated with a URLSessionDownloadTask that has been terminated abnormally due to a network error or other issues? Details Hello, I'm currently developing a feature to download multiple files concurrently on iOS using URLSessionDownloadTask, and I have a question regarding the lifecycle of the temporary files created during this process. As I understand it, URLSessionDownloadTask stores incoming data in a temporary file within the tmp directory, typically with a name like CFNetworkDownload_*.tmp. In my testing, temporary files are managed correctly in the normal scenario. For instance, when I call the cancel() method on an active downloadTask and then release all references to it, the corresponding temporary file is automatically cleaned up from the tmp directory shortly after. However, the problem occurs when a download is interrupted abnormally due to external factors, such as a lost network connection. In this situation, the urlSession(_:task:didCompleteWithError:) delegate method is called, but the associated temporary file is not deleted and remains in the tmp directory. I've observed a particularly interesting behavior related to this. Immediately after the error occurs, if I check my app's storage usage in the iOS Settings app, the data size appears to have decreased momentarily. However, the tmp file has not actually been deleted, and after a short while, the storage usage is recalculated to include the size of this orphaned temporary file. Since my app does not support resuming interrupted downloads, these leftover files become orphaned and unnecessarily consume storage. Therefore, I want to ensure they are all reliably deleted. With this context, I'd like to ask the community: What is the standard, most reliable way to manage temporary files associated with a URLSessionDownloadTask that has been terminated abnormally due to a network error or other issues? I am wondering if there is an official guide or a framework-level API to handle these orphaned files. I would appreciate any advice from those with experience in this area. Thank you.
1
0
44
3d
WebAuthenticationSession under a carrier-provided satellite network?
(related post: How to optimize my app for for a carrier-provided satellite network? ) I am trying to implement an app so that it works under a carrier-provided satellite network. The app uses (AS)WebAuthenticationSession for signing in. If the app is entitled to access a satellite network, will (AS)WebAuthenticationSession work as well? How about WKWebView and SFSafariViewController? Is there a way to test(simulate) a ultra-constrained network on a device or a simulator to see the expected behavior? Thanks,
4
0
113
5d
Could not delete cookies on IOS18
Hello, I have encountered an issue with an iPhone 15PM with iOS 18.5. The NSHTTPCookieStorage failed to clear cookies, after clearing them, I was still able to retrieve them. However, on the same system NSHTTPCookie *cookie; NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (cookie in [storage cookies]) { [storage deleteCookie:cookie]; } NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[[self url] absoluteURL]]; // still able to get cookies,why???
1
0
48
2w
How to Keep Cellular Data Active While Connected to a Local Hotspot for File Transfer?
Hi all, I’m developing a companion iOS app that connects to a device-created Wi-Fi hotspot to transfer videos or other files WebSocket. The challenge is: once the iPhone connects to this hotspot, it loses internet access because iOS routes all traffic through Wi-Fi. However, I’d like to keep the iPhone’s cellular data active and usable while staying connected to the local hotspot — so the app can access cloud APIs, or the user can continue using other apps that require internet access. I understand that iOS prioritizes Wi-Fi over cellular, but are there any supported workarounds or patterns (e.g., MFi programs, local-only Wi-Fi access, NEHotspotConfiguration behavior, etc.) that : • Using Wi-Fi only for local communication; • cellular to remain active for internet access. Any insights or Apple-recommended best practices would be greatly appreciated — especially any official references regarding MFi Accessory setup or NEHotspotConfiguration behavior in this context. Thanks in !
1
0
43
3w
Requested NSURLSession task is neither requested nor has it timed out
Our application has initiated an NSURLSession data task, and we have received an initiation ID. However, Application not received callback on the subsequent activity: the task has not been requested, has not timed out, and no error callback has been received. [06/17 09:29:40:559][ 0x282a7d8c0] Requested TaskIdentifier 120 2025-06-17 09:29:40.623337 +0530 nsurlsessiond SUBMITTING: com.apple.CFNetwork-cc-166-373-Task .<120>:A71666 default 2025-06-17 09:29:40.631280 +0530 dasd Submitted Activity: com.apple.CFNetwork-cc-166-373-Task .<120>:A71666 at priority 10 default Seen couple of rejection with for CPUUsagePolicy and MemoryPressurePolicy 2025-06-17 09:29:40.989360 +0530 dasd com.apple.CFNetwork-cc-166-373-Task .<120>:A71666:[ {name: CPUUsagePolicy, policyWeight: 5.000, response: {Decision: Must Not Proceed, Score: 0.00, Rationale: [{[Max allowed CPU Usage level]: Required:90.00, Observed:95.00},]}} {name: MemoryPressurePolicy, policyWeight: 5.000, response: {Decision: Must Not Proceed, Score: 0.00, Rationale: [{[memoryPressure]: Required:1.00, Observed:2.00},]}} ], FinalDecision: Must Not Proceed} default 2025-06-17 10:55:22.500277 +0530 dasd com.apple.CFNetwork-cc-166-373-Task .<120>:A71666:[ {name: MemoryPressurePolicy, policyWeight: 5.000, response: {Decision: Must Not Proceed, Score: 0.00, Rationale: [{[memoryPressure]: Required:1.00, Observed:2.00},]}} ], FinalDecision: Must Not Proceed} default And more an hour later then it throws with an error BUT NEVER indicated the same to client 2025-06-17 10:55:27.426549 +0530 WAVE PTX Task .<120> is for <>.<>.<120> default 2025-06-17 10:55:27.776951 +0530 nsurlsessiond Task .<120> summary for task failure {transaction_duration_ms=5147145, response_status=-1, connection=0, reused=1, request_start_ms=0, request_duration_ms=0, response_start_ms=0, response_duration_ms=0, request_bytes=0, response_bytes=0, cache_hit=false} default 2025-06-17 10:55:27.777096 +0530 nsurlsessiond NDSession <714296D7-20F9-4A0A-8C31-71FB67F39A56> Task .<120> for client will be retried after error Error Domain=_nsurlsessiondErrorDomain Code=6 UserInfo={NSErrorFailingURLStringKey=, NSErrorFailingURLKey=, _NSURLErrorRelatedURLSessionTaskErrorKey=, _NSURLErrorFailingURLSessionTaskErrorKey=} - code: 6 default Then It got resumed and says successful but never got any callback on the same to client 2025-06-17 10:55:28.877245 +0530 nsurlsessiond NDSession <714296D7-20F9-4A0A-8C31-71FB67F39A56> Task .<120> resuming default 2025-06-17 10:55:55.225456 +0530 nsurlsessiond Task .<120> received response, status 401 content K default 2025-06-17 10:55:55.250371 +0530 nsurlsessiond Task .<120> finished successfully default Please refer feedback for diagnose logs: https://feedbackassistant.apple.com/feedback/18173303
5
0
45
11h
Crashed: com.apple.CFNetwork.Connection
Hi, i have a crash received in my Firebase Crashlytics. I couldn't figure out the root cause of the issue. Could anyone please help me with it. Crashed: com.apple.CFNetwork.Connection 0 libobjc.A.dylib 0x20b8 objc_retain_x19 + 16 1 CFNetwork 0x47398 HTTP3Fields::appendField(NSString*, NSString*) + 72 2 CFNetwork 0x41250 invocation function for block in HTTP3Stream::_buildRequestHeaders() + 240 3 CoreFoundation 0x249f0 __NSDICTIONARY_IS_CALLING_OUT_TO_A_BLOCK__ + 24 4 CoreFoundation 0x565dc ____NSDictionaryEnumerate_block_invoke_2 + 56 5 CoreFoundation 0x55b10 CFBasicHashApply + 148 6 CoreFoundation 0x8abfc __NSDictionaryEnumerate + 520 7 CFNetwork 0x793d4 HTTP3Stream::scheduleAndOpenWithHandler(CoreSchedulingSet const*, void (__CFHTTPMessage*, NSObject<OS_dispatch_data>*, CFStreamError const*) block_pointer, void (unsigned char) block_pointer) + 1120 8 CFNetwork 0x1665c HTTPProtocol::useNetStreamInfoForRequest(MetaNetStreamInfo*, HTTPRequestMessage const*, unsigned char) + 4044 9 CFNetwork 0x80c80 HTTP3ConnectionCacheEntry::enqueueRequestForProtocol(MetaConnectionCacheClient*, HTTPRequestMessage const*, MetaConnectionOptions) + 2540 10 CFNetwork 0x7fab8 HTTP3ConnectionCacheWrapper::ingestTube(Tube*, bool) + 2924 11 CFNetwork 0x257dc TubeManager::newTubeReady(Tube*, CFStreamError) + 4284 12 CFNetwork 0x57b64 invocation function for block in TubeManager::_onqueue_createNewTube(HTTPConnectionCacheKey*) + 72 13 CFNetwork 0x2fe30 Tube::_onqueue_invokeCB(CFStreamError) + 360 14 CFNetwork 0x2fc20 NWIOConnection::_signalEstablished() + 652 15 CFNetwork 0x4ba1c invocation function for block in NWIOConnection::_handleEvent_ReadyFinish() + 748 16 CFNetwork 0x4b5b0 invocation function for block in Tube::postConnectConfiguration(NSObject<OS_tcp_connection>*, NSObject<OS_nw_parameters>*, void () block_pointer) + 860 17 CFNetwork 0x4b220 BlockHolderVar<std::__1::shared_ptr<NetworkProxy>, bool, CFStreamError>::invoke_normal(std::__1::shared_ptr<NetworkProxy>, bool, CFStreamError) + 64 18 CFNetwork 0x32f2c ProxyConnectionEstablishment::postProxyConnectionConfiguration(__CFAllocator const*, std::__1::shared_ptr<TransportConnection>, NSObject<OS_nw_parameters>*, __CFHTTPMessage*, HTTPConnectionCacheKey*, std::__1::shared_ptr<MetaAuthClient>, SmartBlockWithArgs<std::__1::shared_ptr<NetworkProxy>, bool, CFStreamError>) + 664 19 CFNetwork 0x32bbc Tube::postConnectConfiguration(NSObject<OS_tcp_connection>*, NSObject<OS_nw_parameters>*, void () block_pointer) + 744 20 CFNetwork 0xc19b0 invocation function for block in NWIOConnection::_setupConnectionEvents() + 2360 21 libdispatch.dylib 0x132e8 _dispatch_block_async_invoke2 + 148 22 libdispatch.dylib 0x40d0 _dispatch_client_callout + 20 23 libdispatch.dylib 0xb6d8 _dispatch_lane_serial_drain + 744 24 libdispatch.dylib 0xc214 _dispatch_lane_invoke + 432 25 libdispatch.dylib 0xd670 _dispatch_workloop_invoke + 1732 26 libdispatch.dylib 0x17258 _dispatch_root_queue_drain_deferred_wlh + 288 27 libdispatch.dylib 0x16aa4 _dispatch_workloop_worker_thread + 540 28 libsystem_pthread.dylib 0x4c7c _pthread_wqthread + 288 29 libsystem_pthread.dylib 0x1488 start_wqthread + 8 [Here is the complete crash report.](https://developer.apple.com/forums/content/attachment/58b5bb7d-7c90-4eec-906c-4fb76861d44b)
2
0
57
Jun ’25
URLSession not working on iOS26/Xcode26
Hi, I’m trying out my app with Xcode 26, running on an iOS 26 simulator. I'm having issues with URLSessions, it crashes when I set the URLSessionConfiguration to default, and if I don’t use the URLSessionConfiguration, it crashes if I use URLSession.shared. When running in a real device, it doesn't crash, but any network request will hang and time out after a while. Is it a known issue in the latest beta versions?
1
0
106
Jun ’25
Crash in URLSessionConfiguration init in Xcode 26.0 beta (17A5241e)
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.
30
24
4.5k
5d
Crash in URLConnectionLoader::loadWithWhatToDo
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
2
0
89
Jun ’25
Instruments Network: Background URLSession instance appears not to complete
As stated in the title. I am running the following code. Each time I perform an API call, I create a new instance of URLSession and use a background-configured session to allow background API calls. ` Code being executed: import Foundation // Model definitions struct RandomUserResponse: Codable { let results: [RandomUser] } struct RandomUser: Codable { let name: Name let email: String } struct Name: Codable { let first: String let last: String } // Fetcher class class RandomUserFetcher: NSObject, URLSessionDataDelegate { private var receivedData = Data() private var completion: ((RandomUser?) -&gt; Void)? private var session: URLSession! func fetchRandomUserInBackground(completion: @escaping (RandomUser?) -&gt; Void) { self.completion = completion let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.randomuser.bg") session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) let url = URL(string: "https://randomuser.me/api/" )! let task = session.dataTask(with: url) task.resume() } // Data received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { receivedData.append(data) } // Completion func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { defer { self.session.finishTasksAndInvalidate() } guard error == nil else { print("Error: \(error!)") completion?(nil) return } do { let response = try JSONDecoder().decode(RandomUserResponse.self, from: receivedData) completion?(response.results.first) } catch { print("Decoding error: \(error)") completion?(nil) } } }` Called in viewDidLoad, etc.: let fetcher = RandomUserFetcher() fetcher.fetchRandomUserInBackground { user in if let user = user { print("Name: \(user.name.first) \(user.name.last), Email: \(user.email)") } else { print("Failed to fetch random user.") } } In Instruments' Network instrument, I focus on my app's process, use 'Command + 3', and switch to 'List: URLSessionTasks'. Even though didCompleteWithError is called and the API call fully completes, the Duration keeps increasing, and the Success column remains '-' (neither 'Yes' nor 'No'). For non-background URLSessions, the session shows up as 'unnamed session', but for background URLSessions, it appears as 'unnamed background session 1 (XXXXXX-XXXXXX-XXXXX)'. Does this mean the session is not actually being completed? I've checked Debug Memory Graph and confirmed there is no NSURLSession memory leak, but is it possible that the app is somehow still retaining session information internally? I also suspect that Instruments may not be able to fully track background URLSession tasks.
3
0
149
Jun ’25
How to delete cookies on IOS18
Hello, I have encountered an issue with an iPhone 15PM with iOS 18.5. The NSHTTPCookieStorage failed to clear cookies, but even after clearing them, I was still able to retrieve them. However, on the same system It is normal on iPhone 14PM. I would like to know the specific reason and whether there are any adaptation related issues. Following code: NSHTTPCookie *cookie; NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (cookie in [storage cookies]) { [storage deleteCookie:cookie]; }
1
0
100
May ’25
QWAC validation
Hello there, Starting from iOS 18.4, support was included for QWAC Validation and QCStatements. Using the official QWAC Validator at: https://eidas.ec.europa.eu/efda/qwac-validation-tool I was able to check that the domain "eidas.ec.europa.eu" has a valid QWAC certificate. However, when trying to obtain the same result using the new API, I do not obtain the same result. Here is my sample playground code: import Foundation import Security import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true @MainActor class CertificateFetcher: NSObject, URLSessionDelegate { private let url: URL init(url: URL) { self.url = url super.init() } func start() { let session = URLSession(configuration: .ephemeral, delegate: self, delegateQueue: nil) let task = session.dataTask(with: url) { data, response, error in if let error = error { print("Error during request: \(error)") } else { print("Request completed.") } } task.resume() } nonisolated func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -&gt; Void) { guard let trust = challenge.protectionSpace.serverTrust else { completionHandler(.cancelAuthenticationChallenge, nil) return } if let certificates = SecTrustCopyCertificateChain(trust) as? [SecCertificate] { self.checkQWAC(certificates: certificates) } let credential = URLCredential(trust: trust) completionHandler(.useCredential, credential) } nonisolated func checkQWAC(certificates: [SecCertificate]) { let policy = SecPolicyCreateSSL(true, nil) var trust: SecTrust? guard SecTrustCreateWithCertificates(certificates as CFArray, policy, &amp;trust) == noErr, let trust else { print("Unable to create SecTrust") return } var error: CFError? guard SecTrustEvaluateWithError(trust, &amp;error) else { print("Trust evaluation failed") return } guard let result = SecTrustCopyResult(trust) as? [String : Any] else { print("No result dictionary") return } let qwacStatus = result[kSecTrustQWACValidation as String] let qcStatements = result[kSecTrustQCStatements as String] print("QWAC Status: \(String(describing: qwacStatus))") print("QC Statements: \(String(describing: qcStatements))") } } let url = URL(string: "https://eidas.ec.europa.eu/")! let fetcher = CertificateFetcher(url: url) fetcher.start() Which prints: QWAC Status: nil QC Statements: nil Request completed. Am I making a mistake while using the Security framework? I would greatly appreciate any help or guidance you can provide.
4
0
119
May ’25
NWConnections in Network Extension Redirected to Proxy
We have a setup where the system uses proxy settings configured via a PAC file. We are investigating how NWConnection behaves inside a Network Extension (NETransparentProxyProvider) with a transparent proxy configuration based on this PAC file. Scenario: The browser makes a connection which the PAC file resolves as "DIRECT" (bypassing the proxy) Our Network Extension intercepts this traffic for analysis The extension creates a new connection using NWConnection to the original remote address. The issue: despite the PAC file’s "DIRECT" decision, NWConnection still respects the system proxy settings and routes the connection through the proxy. Our questions: Is it correct that NWConnection always uses the system proxy if configured ? Does setting preferNoProxies = true guarantee bypassing the system proxy? Additionally: Whitelisting IPs in the Network Extension to avoid interception is not a viable solution because IPs may correspond to multiple services, and the extension only sees IP addresses, not domains (e.g., we want to skip scanning meet.google.com traffic but still scan other Google services on the same IP range). Are there any recommended approaches or best practices to ensure that connections initiated from a Network Extension can truly bypass the proxy (for example, for specific IP ranges or domains)?
1
0
82
May ’25
URLSession download looping indefinitely until it times out
Hi, I’m trying to download a remote file in the background, but I keep getting a strange behaviour where URLSession download my file indefinitely during a few minutes, without calling urlSession(_:downloadTask:didFinishDownloadingTo:) until the download eventually times out. To find out that it’s looping, I’ve observed the total bytes written on disk by implementing urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:). Note that I can't know the size of the file. The server is not able to calculate the size. Below is my implementation. I create an instance of URLSession like this: private lazy var session: URLSession = { let configuration = URLSessionConfiguration.background(withIdentifier: backgroundIdentifier) configuration.isDiscretionary = false configuration.sessionSendsLaunchEvents = true return URLSession(configuration: configuration, delegate: self, delegateQueue: nil) }() My service is using async/await so I have implemented an AsyncThrowingStream : private var downloadTask: URLSessionDownloadTask? private var continuation: AsyncThrowingStream&lt;(URL, URLResponse), Error&gt;.Continuation? private var stream: AsyncThrowingStream&lt;(URL, URLResponse), Error&gt; { AsyncThrowingStream&lt;(URL, URLResponse), Error&gt; { continuation in self.continuation = continuation self.continuation?.onTermination = { @Sendable [weak self] data in self?.downloadTask?.cancel() } downloadTask?.resume() } } Then to start the download, I do : private func download(with request: URLRequest) async throws -&gt; (URL, URLResponse) { do { downloadTask = session.downloadTask(with: request) for try await (url, response) in stream { return (url, response) } throw NetworkingError.couldNotBuildRequest } catch { throw error } } Then in the delegate : public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let response = downloadTask.response, downloadTask.error == nil, (response as? HTTPURLResponse)?.statusCode == 200 else { continuation?.finish(throwing: downloadTask.error) return } do { let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let savedURL = documentsURL.appendingPathComponent(location.lastPathComponent) try FileManager.default.moveItem(at: location, to: savedURL) continuation?.yield((savedURL, response)) continuation?.finish() } catch { continuation?.finish(throwing: error) } } I also tried to replace let configuration = URLSessionConfiguration.background(withIdentifier: backgroundIdentifier) by let configuration = URLSessionConfiguration.default and this time I get a different error at the end of the download: Task &lt;0457F755-9C52-4CFB-BDB2-F378D0C94912&gt;.&lt;1&gt; failed strict content length check - expected: 0, received: 530692, received (uncompressed): 0 Task &lt;0457F755-9C52-4CFB-BDB2-F378D0C94912&gt;.&lt;1&gt; finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https:/&lt;host&gt;:8190/proxy?Func=downloadVideoByUrl&amp;SessionId=slufzwrMadvyJad8Lkmi9RUNAeqeq, NSErrorFailingURLKey=https://&lt;host&gt;:8190/proxy?Func=downloadVideoByUrl&amp;SessionId=slufzwrMadvyJad8Lkmi9RUNAeqeq, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDownloadTask &lt;0457F755-9C52-4CFB-BDB2-F378D0C94912&gt;.&lt;1&gt;" ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask &lt;0457F755-9C52-4CFB-BDB2-F378D0C94912&gt;.&lt;1&gt;, NSUnderlyingError=0x300d9a7c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=&lt;CFData 0x302139db0 [0x1fcb1f598]&gt;{length = 16, capacity = 16, bytes = 0x10021ffe91e227500000000000000000}}}} The log "failed strict content length check” made me look into the response header, which has the following: content-length: 0 Content-Type: application/force-download Transfer-encoding: chunked Connection: KEEP-ALIVE Content-Transfer-Encoding: binary So it should be fine the way I setup my URLSession. The download works fine in Chrome/Safari/Chrome or Postman. My code used to work a couple of weeks before, so I expect something has changed on the server side, but I can’t find what, and I don’t get much help from the guys on the server side. Has anyone an idea of what’s going on?
1
0
75
May ’25
Background Download Support for Large Video Files in visionOS App
Hi everyone, I'm developing a visionOS app that allows users to download large video files (similar to a movie download experience, with each file being around 10 GB). I've successfully implemented the core video download functionality using URLSession, and everything works as expected while the app is active. Now, I’m looking to support background downloading. Specifically, I want users to be able to start a download and then leave the app (e.g., switch apps or return to the home screen) while the download continues in the background. Additionally, I’d like to confirm a specific scenario: If the user starts a download, then removes the headset (keeping the device turned on and connected to power), will the download continue in the background? Or does visionOS suspend the app or downloads in this case? I’m considering using a background URLSessionConfiguration (as done in iOS/macOS) to enable this behavior, but I’m not sure if it behaves the same way on visionOS or if there are special limitations or best practices when handling large downloads on this platform. Any insights or official guidance would be greatly appreciated! Thanks!
1
0
43
May ’25
URLSessionWebSocketTask reports closeCode as invalid when state is completed
I am using a URLSessionWebSocketTask. When trying to receive messages while the app is backgrounded, the receive() method fails with an NSError where the domain is NSPOSIXErrorDomain and the code is ECONNABORTED. That behavior is good. However, when this happens, the URLSessionWebSocketTask reports a closeCode of invalid, which is supposed to denote that the connection is still open. However, the connection state property is reporting completed. I feel that the closeCode property should be reporting something like abnormalClosure in this case. Either way, this seems like a bug or the documentation is incorrect.
2
3
88
Apr ’25
Hide OS logs coming out of the Network framework (category: com.apple.network)
I'm establishing a connection with NWListener and NWConnection which is working great. However, if the listener disappears, a lot of logs are appearing: Is there a way to hide these logs? I'm aware of OS_ACTIVITY_MODE=disabled, but that will also hide a lot of other logs. I also know you can hide these using Xcode's filtering. I'm looking for a programmatically way to hide these completely. I'm not interested in seeing these at all, or, at least, I want to be in control. Thanks!
4
0
76
Apr ’25
WKWebView Fails with NSURLErrorDomain Code=-1005 on iOS 18.4 Simulator
Hello, I'm experiencing an issue where WKWebView consistently fails to load a specific URL on the iOS 18.4 simulator (Xcode 16.3). The error is as follows: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={ _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4, NSUnderlyingError=Error Domain=kCFErrorDomainCFNetwork Code=-1005, NSErrorFailingURLKey=[REDACTED] } Key Observations: This URL fails consistently only on the iOS 18.4 simulator. The same URL loads without issue in iOS 18.3 and 18.2 simulators. The backend is serving a valid HTTPS certificate chain, and the server appears to be presenting it properly. The same application appears to work on a real iPhone running 18.4. Certificate Chain for the Failing URL Leaf: WR3 (Valid: Mar 17, 2025 – Jun 15, 2025) Intermediate 1: GTS Root R1 (Valid: Dec 13, 2023 – Feb 20, 2029) Intermediate 2: GlobalSign Root CA (Valid: Jun 19, 2020 – Jan 28, 2028) Other URLs Work Fine in iOS 18.4 Simulator WKWebView successfully loads the following URLs with similar or more complex certificate chains: https://google.com → WR2, GTS Root R1, GlobalSign Root CA https://amazon.com → DigiCert Global CA G2, DigiCert Global Root G2, VeriSign G5 https://stackoverflow.com → E5, ISRG Root X1 https://shopify.com → GlobalSign Root CA, GTS Root R4, WE1 This suggests the issue may not be with general network or certificate trust but instead something specific about how iOS 18.4 handles this domain or certificate configuration in the simulator. Any insights on how to solve this would be greatly appreciated.
1
0
166
Apr ’25
URLSessionConfiguration to set usesClassicLoadingMode as false
When i try to set the value ‘false’ for ‘usesClassicLoadingMode’ it is getting crashed. The crash logs has been shared below Ex: let config = URLSessionConfiguration.default if #available(iOS 18.4, *) { config.usesClassicLoadingMode = false } Error log : *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFBoolean objectForKeyedSubscript:]: unrecognized selector sent to instance 0x1f655c390' *** First throw call stack: (0x188ae52ec 0x185f69a7c 0x188b4f67c 0x1889fcb84 0x1889fc4f0 0x191393bc8 0x1889ec8a0 0x1889ec6e4 0x191393ad0 0x191344dac 0x191344b58 0x107cfa064 0x107ce36d0 0x191343fcc 0x1891b3b18 0x1892dae58 0x189235c60 0x18921e270 0x18921d77c 0x18921a8ac 0x107ce0584 0x107cfa064 0x107ce891c 0x107ce95d8 0x107ceabcc 0x107cf5894 0x107cf4eb0 0x212f51660 0x212f4e9f8) terminating due to uncaught exception of type NSException Can you please provider the resolution steps
14
0
190
Apr ’25