General:
TN3151 Choosing the right networking API
Networking Overview document — Despite the fact that this is in the archive, this is still really useful.
TLS for App Developers DevForums post
Choosing a Network Debugging Tool documentation
WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi?
TN3135 Low-level networking on watchOS
Adapt to changing network conditions tech talk
Foundation networking:
DevForums tags: Foundation, CFNetwork
URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms.
Network framework:
DevForums tag: Network
Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms.
Network Extension (including Wi-Fi on iOS):
See Network Extension Resources
Wi-Fi Fundamentals
Wi-Fi on macOS:
DevForums tag: Core WLAN
Core WLAN framework documentation
Wi-Fi Fundamentals
Secure networking:
DevForums tags: Security
Apple Platform Security support document
Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS).
Available trusted root certificates for Apple operating systems support article
Requirements for trusted certificates in iOS 13 and macOS 10.15 support article
About upcoming limits on trusted certificates support article
Apple’s Certificate Transparency policy support article
Technote 2232 HTTPS Server Trust Evaluation
Technote 2326 Creating Certificates for TLS Testing
QA1948 HTTPS and Test Servers
Miscellaneous:
More network-related DevForums tags: 5G, QUIC, Bonjour
On FTP DevForums post
Using the Multicast Networking Additional Capability DevForums post
Investigating Network Latency Problems DevForums post
Local Network Privacy FAQ DevForums post
Extra-ordinary Networking DevForums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
CFNetwork
RSS for tagAccess network services and handle changes in network configurations using CFNetwork.
Posts under CFNetwork tag
75 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
When user opened my application, it crashed immediately.
This is crash log message from firebase.
com.apple.CFNetwork.Connection
EXC_BAD_ACCESS KERN_INVALID_ADDRESS
After restarting iPhone, user can use my application without crash.
I cannot reproduce this crash from other device.
Here are .ips crash log that I changed to .txt.
crashLog-2024-12-26-182447.txt
crashLog-2024-12-26-182449.000.txt
crashLog-2024-12-26-182535.000.txt
crashLog-2024-12-26-182535.txt
Do you have any idea to fix this?
I used the SSH approach method in the post https://developer.apple.com/forums/thread/703234 to add TLS trust for the local accessory device with a self signed certificate.
In the Info.plist, I disabled App Transport Security for local networking by setting the NSAllowsLocalNetworking property, as mentioned in the post.
However, I am still encountering the following SSL error:
ATS failed system trust
Connection 3: system TLS Trust evaluation failed(-9802)
Connection 3: TLS Trust encountered error 3:-9802
Connection 3: encountered error(3:-9802)
Task <9432C2C5-C7A1-44E4-95CC-2AFA49D6C501>.<1> HTTP load failed, 0/0 bytes (error code: -1200 [3:-9802])
Task <9432C2C5-C7A1-44E4-95CC-2AFA49D6C501>.<1> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3
In the code everything is working fine. The certificates are compared and
CFEqual(expected, actual), is returning true. Also in urlSession delegate method , the
return completionHandler(.useCredential, credential)
is returned.
When I disable ATS in Info.plist by setting NSAllowsArbitraryLoads, it works fine.
I have the following questions:
Should I disable ATS by setting NSAllowsArbitraryLoads along with setting ?
Instead of accepting the server certificate for the first time and saving it in the app, why can’t we embed the self-signed certificate in the app directly and use it for comparison?
Hi Team
We are facing a problem in our app for one particular user the url session is giving below error. Rest for all the users its working fine. Below is the complete error we get from user device.
{"type":"video_player","error":"Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=https://api.vimeo.com/videos/1020892798, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<4>, _NSURLErrorRelatedURLSessionTaskErrorKey=(\n "LocalDataTask .<4>"\n), NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://api.vimeo.com/videos/1020892798, NSUnderlyingError=0x301ea8930 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9836, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9836, _NSURLErrorNWPathKey=satisfied (Path is satisfied), viable, interface: pdp_ip0, ipv6, dns, expensive, uses cell}}, _kCFStreamErrorCodeKey=-9836}"}
Device info
device_type iOS
device_os_version 18.1.1
device_model iPhone 11
Please let me know how we can resolve for one particular user. Or what we can adivse.
I have implemented SSL pinning by following this article https://developer.apple.com/news/?id=g9ejcf8y , however pen testing team was able to bypass SSL pinning using Objection & Frida tools.
I am using URLSession for API calls. I used Xcode 16. My app's minimum iOS deployment version is 16 onwards.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSPinnedDomains</key>
<dict>
<key>*.mydomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSPinnedCAIdentities</key>
<array>
<dict>
<key>SPKI-SHA256-BASE64</key>
<string>my SHA256 key</string>
</dict>
</array>
</dict>
</dict>
</dict>
Could anyone suggest how to mitigate this bypass mechanism?
Hello,
I am planning to create an app that can transfer files to hardware devices via WiFi. With devices like GoPro, I believe the typical setup involves the GoPro creating a WiFi hotspot to which the iOS app connects, allowing file transfers. But this setup establishes a 1:1 connection between the app and the hardware.
To support multiple hardware devices simultaneously, I am considering reversing this setup: the iOS device would create a personal hotspot, and the hardware devices would connect to it. However, I have concerns about this approach:
Reliability: I have read that the personal hotspot feature on iOS devices can be unreliable, especially with non-Apple devices, which tend to disconnect frequently.
Manual Setup: There is no API to programmatically create the personal hotspot, so users would have to enable it manually in the Settings.
I can use isIdleTimerDisabled to prevent the iOS screen from going to sleep, which might help with disconnection issues. Aside from this, are there other things I can do to ensure a stable connection?
Given my limited experience with hardware connections, I am uncertain if having the iOS device act as the WiFi access point is a good design. Any advice or alternative solutions would be greatly appreciated.
Thank you in advance!
Hi, I have been working on the app that implements DNS Proxy Extension for a while now, and after a couple builds to TestFlight I noticed that I got a couple crashes that seem to be triggered by EXC_BREAKPOINT (SIGTRAP)
After some investigation, it was found that crashes are connected to CFNetwork framework. So, I decided to additionally look into memory issues, but I found the app has no obvious memory leaks, no memory regression (within recommended 25%, actual value is at 20% as of right now), but the app still uses 11mb of memory footprint and most of it (6.5 mb is Swift metadata).
At this point, not sure what's triggering those crashes, but I noticed that sometimes app will return message like this to the console (this example is for PostHog api that I use in the app):
Task <0ABDCF4A-9653-4583-9150-EC11D852CA9E>.<1> finished with error [18 446 744 073 709 550 613] Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={_kCFStreamErrorCodeKey=8, NSUnderlyingError=0x1072df0f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, _NSURLErrorNWResolutionReportKey=Resolved 0 endpoints in 2ms using unknown from cache, _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0[802.11], ipv4, dns, uses wifi}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <0ABDCF4A-9653-4583-9150-EC11D852CA9E>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalUploadTask <0ABDCF4A-9653-4583-9150-EC11D852CA9E>.<1>"
), NSLocalizedDescription=A server with the specified hostname could not be found., NSErrorFailingURLStringKey=https://us.i.posthog.com/batch, NSErrorFailingURLKey=https://us.i.posthog.com/batch, _kCFStreamErrorDomainKey=12}
If DNS Proxy Provider uses custom DoH server for resolving packets, could the cache policy for URLSession be a reason?
I had a couple other ideas (HTTP3 failure, CFNetwork core issues like described here) but not sure if they are valid
Would be grateful if someone could give me a hint of what I should look at
My app often fails to access the network (other apps on the device can access the network normally), and restarting the app is also ineffective. I need to open and close the flight mode to restore the app's network
I used to suspect the background refresh was the cause, but removing the background refresh still occasionally causes this problem.
After update to IOS18, my app crashed. following is the exception got from xcode:
Trapped uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSFileManager createDirectoryAtURL:withIntermediateDirectories:attributes:error:]: URL is nil'
(
0 CoreFoundation 0x0000000194a79098 47427277-EE15-3C17-AD68-6886B0380B5E + 540824
1 libobjc.A.dylib 0x0000000191d7b2e4 objc_exception_throw + 88
2 Foundation 0x0000000193741f48 12E17A7A-B65F-35EE-82D7-CBC31004E223 + 1154888
3 CFNetwork 0x0000000195eeb2bc FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 164540
4 CFNetwork 0x0000000195eeac7c FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 162940
5 libdispatch.dylib 0x000000010342a71c _dispatch_client_callout + 20
6 libdispatch.dylib 0x000000010343bf04 _dispatch_lane_barrier_sync_invoke_and_complete + 176
7 CFNetwork 0x0000000195eeaa88 FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 162440
8 CFNetwork 0x0000000195ee9b20 FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 158496
9 CFNetwork 0x0000000195ee95f4 FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 157172
10 CFNetwork 0x0000000195ee907c FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 155772
11 CFNetwork 0x0000000195ee34b0 FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 132272
12 CFNetwork 0x0000000195f942c4 FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 856772
13 CFNetwork 0x0000000195f94214 FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 856596
14 CFNetwork 0x0000000195f9330c FA95B718-E8EB-34BD-90FA-8FB1AFE016D6 + 852748
15 libdispatch.dylib 0x0000000103428a30 _dispatch_call_block_and_release + 32
16 libdispatch.dylib 0x000000010342a71c _dispatch_client_callout + 20
17 libdispatch.dylib 0x00000001034325e8 _dispatch_lane_serial_drain + 828
18 libdispatch.dylib 0x0000000103433394 _dispatch_lane_invoke + 460
19 libdispatch.dylib 0x0000000103434b20 _dispatch_workloop_invoke + 2264
20 libdispatch.dylib 0x00000001034405f0 _dispatch_root_queue_drain_deferred_wlh + 328
21 libdispatch.dylib 0x000000010343fc00 _dispatch_workloop_worker_thread + 580
22 libsystem_pthread.dylib 0x000000021bddfc7c _pthread_wqthread + 288
23 libsystem_pthread.dylib 0x000000021bddc488 start_wqthread + 8
)
This app works fine until ios 18 appear. Could you help me? thanks
Our app has been crashing in the CFNetwork Framework frequently, but the attached TestFlight crash logs do not help in identifying the possible root cause of the same. Any help would be greatly appreciated.
We found there is a significant crash reports (most of them are from iOS 17, the rest are iOS 16 and 15) comes from network loader from CFNetwork. Apparently it seems there are two types of crashes if we checked from the stack trace, the one we found from both Xcode organizer and 3rd party crash reporter is referring to URLConnectionLoader::loadWithWhatToDo and the other one from our 3rd party crash reporter (didn’t found the report from Xcode organizer) referring to
_CFURLResponseCreateFromArchiveList (this one only happened on iOS 17.5 and later devices). It seems that they are both kinda similar which might point to the same root cause.
From what I’ve seen, we never touch the lower level API directly, we usually use the URLSession to manage our API request. The crashed stack trace also didn’t give any indication about which of our app code that triggered the crash, it only shows calls to Apple’s internal SDKs so we are unsure how to approach this issue meanwhile the crash event already reached 800+ in the last 30 days. Unfortunately, we cannot reproduce the issue as the stack trace itself seems unclear to us.
I have submitted a report through feedback assistant with number: FB14679252.
Would appreciate if anyone can give any advice on what we can do to avoid this in the future and probably any hint on why it could happened.
Hereby I attached the crash reports that we found each from Xcode crash report and our 3rd party crash reporter (the report said it crashed on com.apple.CFNetwork.LoaderQ) so you could get a glimpse of the similarity.
Xcode crash report
xcode crash report.crash
3rd party crash report
3rd party crash report.txt
com.apple.CFNetwork.LoaderQ EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000058
iOS 13.7.0
iPhone 8 Plus
Crashed: com.apple.CFNetwork.LoaderQ
0 libdispatch.dylib 0x4414c dispatch_source_set_timer$VARIANT$armv81 + 28
1 CFNetwork 0x172ad0 _CFNetworkSetATSContext + 86396
2 CFNetwork 0x172f58 _CFNetworkSetATSContext + 87556
3 CFNetwork 0x170194 _CFNetworkSetATSContext + 75840
4 CFNetwork 0x21c640 _CFURLStorageSessionCopyCache + 60116
5 libdispatch.dylib 0x5a9a8 _dispatch_call_block_and_release + 24
6 libdispatch.dylib 0x5b524 _dispatch_client_callout + 16
7 libdispatch.dylib 0x38b3c _dispatch_lane_serial_drain$VARIANT$armv81 + 564
8 libdispatch.dylib 0x39580 _dispatch_lane_invoke$VARIANT$armv81 + 448
9 libdispatch.dylib 0x3a5e8 _dispatch_workloop_invoke$VARIANT$armv81 + 1544
10 libdispatch.dylib 0x4284c _dispatch_workloop_worker_thread + 580
11 libsystem_pthread.dylib 0xbb74 _pthread_wqthread + 272
12 libsystem_pthread.dylib 0xe740 start_wqthread + 8
Hello i have one question about currentSSID meaning in PLWIFIAGENT_EVENTBACKWARD_CUMULATIVEPROPERTIES table in powerlog DB in iOS 14.
It looks like a 32 character long hex string, what does it mean? e.g. MAC, bssid or ssid encryption?
I need to programatically connect to a Enterprise Network with security type EAP-PEAP.
NEHotspotEAPSettings *eapSettings = [[NEHotspotEAPSettings alloc] init];
eapSettings.username = username;
eapSettings.password = password;
eapSettings.supportedEAPTypes = [NSArray arrayWithObjects:[NSNumber numberWithInteger:NEHotspotConfigurationEAPTypeEAPPEAP], nil];
//Inner authentication
eapSettings.ttlsInnerAuthenticationType = NEHotspotConfigurationEAPTTLSInnerAuthenticationMSCHAPv2;
eapSettings.outerIdentity = @"";
//Server name of the network
eapSettings.trustedServerNames = @[@"servername"];
if (@available(iOS 11.0, *)) {
// Create Hotspot Configuration
NEHotspotConfiguration *configuration = [[NEHotspotConfiguration alloc] initWithSSID:ssid eapSettings:eapSettings];
NSLog(@"WIFIManager, NEHotspotConfiguration initialized");
[[NEHotspotConfigurationManager sharedManager] applyConfiguration:configuration completionHandler:^(NSError * _Nullable error) {
NSLog(@"WIFIManager, NEHotspotConfiguration Configured");
if (error != nil) {
NSLog(@"WIFIManager, NEHotspotConfiguration Error: %@", error);
if (error.code == NEHotspotConfigurationErrorAlreadyAssociated) {
resolve(@(YES));
} else {
reject(@"connection_error", @"Failed to connect to Wi-Fi", error);
}
} else {
resolve(@(YES));
NSLog(@"WIFIManager, NEHotspotConfiguration Success");
}
}];
}else {
reject(@"ios_error", @"Not supported in iOS<11.0", nil);
} }
This is the code I have tried to connect to the network. It is always giving a true-negative result.
As the documentation states, does NEHotspotConfigurationManager supports EAP-PEAP with MSCHAPv2 inner authentication? If it does, is it the correct way of implementing it?
Is there any other way to connect to EAP-PEAP networks using Swift or Objective C?
I have a simple SwiftUI application that sends a URLRequest as shown in the code snippet below:
import SwiftUI
@main
struct GOGODemoApp: App {
var body: some Scene {
WindowGroup {
MyView()
}
}
}
struct MyView: View {
var body: some View {
Button("Click") {
sendHTTPRequest(to: "https://www.google.com") { code, err in
print("Finished, code: \(code ?? -1), err: \(String(describing: err))")
}
}
}
}
func sendHTTPRequest(to urlString: String, completion: @escaping (Int?, Error?) -> Void) {
guard let url = URL(string: urlString) else {
completion(nil, NSError(domain: "InvalidURL", code: 0, userInfo: nil))
return
}
let task = URLSession.shared.dataTask(with: url) { _, resp, error in
if let httpResponse = resp as? HTTPURLResponse {
completion(httpResponse.statusCode, error)
} else {
completion(-1, error)
}
}
task.resume()
}
However, Xcode prints the following warning messages:
nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint
nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint
nw_connection_copy_connected_local_endpoint_block_invoke [C3] Connection has no local endpoint
nw_connection_copy_connected_local_endpoint_block_invoke [C3] Connection has no local endpoint
Finished, code: 200, err: nil
What does the warning 'Connection has no local endpoint' mean?
Thank you for your assistance!
I'm very interested in whether it works and, if so, how the system decides to enable or not TFO when working with the network using URLSession.
I didn't find any information in the documentation.
For example, for NWConnection we need to manually add additional option:
/* Allow fast open on the connection parameters */
parameters.allowFastOpen = true
let connection = NWConnection(to: endpoint, using: parameters)
/* Call send with idempotent initial data before starting the connection */
connection.send(content: initialData, completion: .idempotent)
connection.start(queue: myQueue)
Hi Team,
There is situation in which I want to implement session Resumption in IOS. I am using Network Framework but I am unable to find a way, how to enable the resumption . It will more beneficial for me if you guys can help me in that.
Regards,
When using Network framework, is it possible to set NWProtocolTLS behave like TLS Server or Client? In CFNetwork there is a kCFStreamSSLIsServer key which I could not find the same thing in Network.
I currently try to implement something like STARTTLS, both client and server side, after connection and some message, the client will behave like a TLS SERVER, and the connection in server(NWListener) will behave like a TLS CLIENT.
That's why i need to set something like kCFStreamSSLIsServer
In Swift-NIO, this can be easily implemented by adding a NIOSSLClientHandler or NIOSSLServerHandler
Below it's what I got currently based on another post in community
// main.swift
import Foundation
import Network
let params = NWParameters.tcp
let framer = STARTTLSFramer.options()
params.defaultProtocolStack.applicationProtocols = [framer]
let connection = NWConnection(
host: .ipv4(IPv4Address("127.0.0.1")!), port: .init(integerLiteral: 8089), using: params)
connection.stateUpdateHandler = { newState in
print("connection newState \(newState)")
}
connection.start(queue: .main)
RunLoop.main.run()
// STARTLSFramer.swift
import Foundation
import Network
final class STARTTLSFramer: NWProtocolFramerImplementation {
static let label: String = "STARTTLSFramer"
init(framer: NWProtocolFramer.Instance) {}
func handleOutput(
framer instance: NWProtocolFramer.Instance, message: NWProtocolFramer.Message,
messageLength: Int, isComplete: Bool
) {
fatalError()
}
func wakeup(framer instance: NWProtocolFramer.Instance) {
fatalError()
}
func stop(framer instance: NWProtocolFramer.Instance) -> Bool { true }
func cleanup(framer instance: NWProtocolFramer.Instance) {}
func start(framer instance: NWProtocolFramer.Instance) -> NWProtocolFramer.StartResult {
instance.writeOutput(data: Data("hello\n".utf8))
return .willMarkReady
}
private var accumulated = Data()
func doUpgrade(instance: NWProtocolFramer.Instance) {
let tlsOptions = NWProtocolTLS.Options()
sec_protocol_options_set_min_tls_protocol_version(tlsOptions.securityProtocolOptions, .TLSv12)
// load identity
let secIdentity = createSecIdentity()!
let identity = sec_identity_create(secIdentity)
sec_protocol_options_set_local_identity(tlsOptions.securityProtocolOptions, identity!)
try! instance.prependApplicationProtocol(options: tlsOptions)
instance.passThroughOutput()
instance.passThroughInput()
instance.markReady()
}
func handleInput(framer instance: NWProtocolFramer.Instance) -> Int {
repeat {
let success = instance.parseInput(minimumIncompleteLength: 1, maximumLength: 2048) {
buffer, _ in
let count = buffer?.count ?? 0
if let buffer {
accumulated.append(contentsOf: buffer)
}
return count
}
if !success { break }
} while true
// some validation
self.accumulated.removeAll()
self.doUpgrade(instance: instance)
return 0
}
static func options() -> NWProtocolFramer.Options {
let startTLSDef = NWProtocolFramer.Definition(implementation: STARTTLSFramer.self)
let result = NWProtocolFramer.Options(definition: startTLSDef)
return result
}
}
Looking into making requests using URLSession via a proxy, on watchOS, and found that in URLSessionConfiguration, there's a proxyConfigurations property.
However, since ProxyConfiguration is part of the Network framework, does it means that TN3135 low level networking rules also applies in this case?
When I initiate the following request in the app delegate, it is good in iOS 17, but it will crash in iOS 18.
The code is as below:
NSString *url = @"https://www.baidu.com";
NSString * restr = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:nil];
The stack is as below:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSFileManager createDirectoryAtURL:withIntermediateDirectories:attributes:error:]: URL is nil'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff8004c14d5 __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff800084116 objc_exception_throw + 62
2 Foundation 0x00007ff800f00861 -[NSFileManager contentsOfDirectoryAtPath:error:] + 0
3 CFNetwork 0x00007ff804c66bfd -[_NSHTTPAlternativeServicesStorage _onqueue_initializeDatabaseIfNotEmpty:] + 488
4 CFNetwork 0x00007ff804c69350 __66-[_NSHTTPAlternativeServicesStorage HTTPServiceEntriesWithFilter:]_block_invoke + 48
5 libdispatch.dylib 0x0000000115349f32 _dispatch_client_callout + 8
6 libdispatch.dylib 0x000000011535ad86 _dispatch_lane_barrier_sync_invoke_and_complete + 133
7 CFNetwork 0x00007ff804c65bf7 -[_NSHTTPAlternativeServicesStorage HTTPServiceEntriesWithFilter:] + 211
8 CFNetwork 0x00007ff804cd5ccc _ZN11TubeManager34_onqueue_enqueueRequestForProtocolEP25MetaConnectionCacheClientPK18HTTPRequestMessage21MetaConnectionOptionsP16BaseAwaitingTube + 264
9 CFNetwork 0x00007ff804bf8b0c ___ZN12XTubeManager25enqueueRequestForProtocolEP25MetaConnectionCacheClientPK18HTTPRequestMessage21MetaConnectionOptionsPK17CoreSchedulingSet_block_invoke + 328
10 CFNetwork 0x00007ff804bf8832 _ZN12XTubeManager15withTubeManagerEPK17CoreSchedulingSetU13block_pointerFvP15GlueTubeManagerE + 516
11 CFNetwork 0x00007ff804d27823 _ZN12HTTPProtocol81asynchronouslyCreateAndOpenStream_WithMessage_AfterCookiesAndAuthenticatorHeadersEP15__CFHTTPMessage + 6077
12 CFNetwork 0x00007ff804d25ea3 _ZN12HTTPProtocol48asynchronouslyAddAuthenticatorHeadersAndContinueEP15__CFHTTPMessage + 103
13 CFNetwork 0x00007ff804d295b3 ___ZN12HTTPProtocol35asynchronouslyAddCookiesAndContinueEP15__CFHTTPMessage_block_invoke_3 + 26
14 CFNetwork 0x00007ff804e0fdb7 ___ZNK18QCoreSchedulingSet12performAsyncEU13block_pointerFvvE_block_invoke + 41
15 libclang_rt.asan_iossim_dynamic.dyl 0x0000000115d0fa4c __wrap_dispatch_async_block_invoke + 204
16 libdispatch.dylib 0x0000000115348ba9 _dispatch_call_block_and_release + 12
17 libdispatch.dylib 0x0000000115349f32 _dispatch_client_callout + 8
18 libdispatch.dylib 0x0000000115351e3b _dispatch_lane_serial_drain + 1078
19 libdispatch.dylib 0x0000000115352bbc _dispatch_lane_invoke + 448
20 libdispatch.dylib 0x0000000115353be7 _dispatch_workloop_invoke + 876
21 libdispatch.dylib 0x000000011535fcc6 _dispatch_root_queue_drain_deferred_wlh + 318
22 libdispatch.dylib 0x000000011535f205 _dispatch_workloop_worker_thread + 853
23 libsystem_pthread.dylib 0x000000011521db84 _pthread_wqthread + 327
24 libsystem_pthread.dylib 0x000000011521cacf start_wqthread + 15
)
libc++abi: terminating due to uncaught exception of type NSException
Hi,
I am trying to download multiple files in background (using multiple background urlsession). I initiate the download on click of a button and push the app to background where the download should happen.
I am getting the following error:
Error Domain=NSCocoaErrorDomain Code=4 "“CFNetworkDownload_EYp3BT.tmp” couldn’t be moved to “Documents” because either the former doesn’t exist, or the folder containing the latter doesn’t exist." UserInfo={NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/85AEEB4F-1512-4C0C-8B04-C9C73634CC49/Library/Caches/com.apple.nsurlsessiond/Downloads/com.mycompany.DownloadMultipleFilesTestApp/CFNetworkDownload_EYp3BT.tmp, NSUserStringVariant=(\n Move\n), NSDestinationFilePath=/var/mobile/Containers/Data/Application/85AEEB4F-1512-4C0C-8B04-C9C73634CC49/Documents/file-441966.pdf, NSFilePath=/private/var/mobile/Containers/Data/Application/85AEEB4F-1512-4C0C-8B04-C9C73634CC49/Library/Caches/com.apple.nsurlsessiond/Downloads/com.mycompany.DownloadMultipleFilesTestApp/CFNetworkDownload_EYp3BT.tmp, NSUnderlyingError=0x28155f900 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
In my sample code attached here i am trying with 500 background urlsession (one download task per each url session)
I have implemented the required methods:
application(_:handleEventsForBackgroundURLSession:completionHandler)
and
urlSessionDidFinishEvents forBackgroundURLSession:)
I have found that the error happens because of two callbacks to
urlSession(_:downloadTask:didFinishDownloadingTo:)
where i move the file from temporary location to a location in my app's documents directory.
The first time the file is present at the location, but for the second callback (with same urlsession id, task id and location values) to urlSession(_:downloadTask:didFinishDownloadingTo:) the file isnt present there and so the move fails.
Can someone please explain this erratic behaviour ? Is this a known issue with URLSession ?
For a repro, you can use the code attached above, test on a physical device without running app from xcode ie launch the app from phone's home screen, click on the download button and send the app to background. Check logs in the console app on mac
Test environment:
iPhone 8plus with iOS 16.7.8