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
96 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
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
Hello there~
I just got an app submission rejected and the reason is app crashed on launch (exhausted real time allowance of 19.74 seconds). However, I cannot reproduce the crash on my iPad 6th, iOS 17.5.1 (same OS version used by the reviewer) with app built by Xcode 15.2 and Xcode 15.4.
After I reviewed the logs, I found the last method we called is CNCopyCurrentNetworkInfo, it triggered a series of method invocations , then crashed. But I cannot remove CNCopyCurrentNetworkInfo directly, since I need to get some value from NetworkInfo. So I'm not sure how to solve this issue.
Please give me some advices, thanks!
Thread 8 name: com.apple.CFNetwork.CustomProtocols
1
libobjc.A.dylib
_objc_opt_respondsToSelector (in libobjc.A.dylib)
2
CoreFoundation
__inputStreamCallbackFunc (in CoreFoundation)
3
CoreFoundation
__signalEventSync (in CoreFoundation)
4
CoreFoundation
__cfstream_shared_signalEventSync (in CoreFoundation)
5
CoreFoundation
_CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION (in CoreFoundation)
6
CoreFoundation
___CFRunLoopDoSource0 (in CoreFoundation)
7
CoreFoundation
___CFRunLoopDoSources0 (in CoreFoundation)
8
CoreFoundation
___CFRunLoopRun (in CoreFoundation)
9
CoreFoundation
_CFRunLoopRunSpecific (in CoreFoundation)
10
CFNetwork
_estimatedPropertyListSize (in CFNetwork)
11
Foundation
_NSThread__start (in Foundation)
12
libsystem_pthread.dylib
__pthread_start (in libsystem_pthread.dylib)
13
libsystem_pthread.dylib
_thread_start (in libsystem_pthread.dylib)
We are experiencing an exception issue with CFNetwork in our app that has affected tens of thousands of users. From user feedback and error reports, we've noticed that this issue is primarily occurring on the latest iOS version.
Here is the stack trace we've collected:
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: 0x00000000 at 0000000000000000
Crashed Thread: 8
CrashDoctor Diagnosis: Attempted to dereference null pointer.
Originated at or in a subcall of unknown, cannot find symbol
Thread 8 Crashed:
0 CFNetwork 0x00000001a168626c 0x1a14b6000 + 1901164 (CFHTTPCookieStorageUnscheduleFromRunLoop)
1 CFNetwork 0x00000001a1686c14 0x1a14b6000 + 1903636 (CFHTTPCookieStorageUnscheduleFromRunLoop)
2 CFNetwork 0x00000001a1686c14 0x1a14b6000 + 1903636 (CFHTTPCookieStorageUnscheduleFromRunLoop)
3 CFNetwork 0x00000001a1670c38 0x1a14b6000 + 1813560 (CFHTTPCookieStorageUnscheduleFromRunLoop)
4 CFNetwork 0x00000001a1670ac8 0x1a14b6000 + 1813192 (CFHTTPCookieStorageUnscheduleFromRunLoop)
5 CFNetwork 0x00000001a1669cb0 0x1a14b6000 + 1785008 (CFHTTPCookieStorageUnscheduleFromRunLoop)
6 CFNetwork 0x00000001a166ce0c 0x1a14b6000 + 1797644 (CFHTTPCookieStorageUnscheduleFromRunLoop)
7 CFNetwork 0x00000001a16bd994 0x1a14b6000 + 2128276 (_CFHTTPServerResponseEnqueue)
8 CFNetwork 0x00000001a160b484 0x1a14b6000 + 1397892 (_CFStreamErrorFromCFError)
9 CFNetwork 0x00000001a160b164 0x1a14b6000 + 1397092 (_CFStreamErrorFromCFError)
10 CFNetwork 0x00000001a160a31c 0x1a14b6000 + 1393436 (_CFStreamErrorFromCFError)
11 CFNetwork 0x00000001a16068cc 0x1a14b6000 + 1378508 (_CFStreamErrorFromCFError)
12 CFNetwork 0x00000001a1610f38 0x1a14b6000 + 1421112 (_CFStreamErrorFromCFError)
13 CFNetwork 0x00000001a1610380 0x1a14b6000 + 1418112 (_CFStreamErrorFromCFError)
14 CFNetwork 0x00000001a163b5a8 0x1a14b6000 + 1594792 (_CFStreamErrorFromCFError)
15 CFNetwork 0x00000001a17118f8 0x1a14b6000 + 2472184
16 libdispatch.dylib 0x00000001a827913c 0x1a8277000 + 8508 (_dispatch_call_block_and_release)
17 libdispatch.dylib 0x00000001a827add4 0x1a8277000 + 15828 (_dispatch_client_callout)
18 libdispatch.dylib 0x00000001a8282400 0x1a8277000 + 46080 (_dispatch_lane_serial_drain)
19 libdispatch.dylib 0x00000001a8282f64 0x1a8277000 + 48996 (_dispatch_lane_invoke)
20 libdispatch.dylib 0x00000001a8284284 0x1a8277000 + 53892 (_dispatch_workloop_invoke)
21 libdispatch.dylib 0x00000001a828dcb4 0x1a8277000 + 93364 (_dispatch_root_queue_drain_deferred_wlh)
22 libdispatch.dylib 0x00000001a828d528 0x1a8277000 + 91432 (_dispatch_workloop_worker_thread)
23 libsystem_pthread.dylib 0x00000001fc360f20 0x1fc35f000 + 7968 (_pthread_wqthread)
We have no solutions
We suspect this might be a bug with CFNetwork, as we did not encounter this issue on older iOS versions. We hope for a swift resolution as this issue is impacting a large number of our users. We are more than willing to provide any additional information needed or try any potential solutions. Thank you!"
We are experiencing an exception issue with CFNetwork in our app that has affected tens of thousands of users. From user feedback and error reports, we've noticed that this issue is primarily occurring on the latest iOS version.
Here is the stack trace we've collected:
Thread 54 Crashed:
0 CFNetwork 0x00000001988f1324 0x198721000 + 1901348 (CFHTTPCookieStorageUnscheduleFromRunLoop)
1 CFNetwork 0x00000001988f1ccc 0x198721000 + 1903820 (CFHTTPCookieStorageUnscheduleFromRunLoop)
2 CFNetwork 0x00000001988f1ccc 0x198721000 + 1903820 (CFHTTPCookieStorageUnscheduleFromRunLoop)
3 CFNetwork 0x00000001988dbcf4 0x198721000 + 1813748 (CFHTTPCookieStorageUnscheduleFromRunLoop)
4 CFNetwork 0x00000001988dbb84 0x198721000 + 1813380 (CFHTTPCookieStorageUnscheduleFromRunLoop)
5 CFNetwork 0x00000001988d4d6c 0x198721000 + 1785196 (CFHTTPCookieStorageUnscheduleFromRunLoop)
6 CFNetwork 0x00000001988d7ec8 0x198721000 + 1797832 (CFHTTPCookieStorageUnscheduleFromRunLoop)
7 CFNetwork 0x0000000198927ebc 0x198721000 + 2125500 (_CFHTTPServerResponseEnqueue)
8 CFNetwork 0x0000000198876678 0x198721000 + 1398392 (_CFStreamErrorFromCFError)
9 CFNetwork 0x0000000198876358 0x198721000 + 1397592 (_CFStreamErrorFromCFError)
10 CFNetwork 0x0000000198875510 0x198721000 + 1393936 (_CFStreamErrorFromCFError)
11 CFNetwork 0x0000000198871ac0 0x198721000 + 1379008 (_CFStreamErrorFromCFError)
12 CFNetwork 0x000000019887c7a4 0x198721000 + 1423268 (_CFStreamErrorFromCFError)
13 CFNetwork 0x000000019887b574 0x198721000 + 1418612 (_CFStreamErrorFromCFError)
14 CFNetwork 0x00000001988a66a0 0x198721000 + 1595040 (_CFStreamErrorFromCFError)
15 CFNetwork 0x000000019897bd10 0x198721000 + 2469136
16 libdispatch.dylib 0x000000019f63b6a8 0x19f639000 + 9896 (_dispatch_call_block_and_release)
17 libdispatch.dylib 0x000000019f63d300 0x19f639000 + 17152 (_dispatch_client_callout)
18 libdispatch.dylib 0x000000019f644894 0x19f639000 + 47252 (_dispatch_lane_serial_drain)
19 libdispatch.dylib 0x000000019f6453f8 0x19f639000 + 50168 (_dispatch_lane_invoke)
20 libdispatch.dylib 0x000000019f6466a8 0x19f639000 + 54952 (_dispatch_workloop_invoke)
21 libdispatch.dylib 0x000000019f650004 0x19f639000 + 94212 (_dispatch_root_queue_drain_deferred_wlh)
22 libdispatch.dylib 0x000000019f64f878 0x19f639000 + 92280 (_dispatch_workloop_worker_thread)
23 libsystem_pthread.dylib 0x000000020162f964 0x20162e000 + 6500 (_pthread_wqthread)
We suspect this might be a bug with CFNetwork, as we did not encounter this issue on older iOS versions. We hope for a resolution as this issue is impacting a large number of our users. We are more than willing to provide any additional information needed or try any potential solutions. Thank you!"
There are several crash logs
Crashed: com.apple.root.default-qos
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000038
0 CFNetwork 0x1e98 CFURLRequestSetHTTPRequestBody + 36
1 *** 0x104f7d0 -[XXXRequest getURLRequest] + 66 (XXXRequest.m:66)
2 *** 0x1051328 -[XXXRequestManager processHTTPRequest:] + 152 (XXXRequestManager.m:152)
3 *** 0x79748c __47-[XXXLog __submit:]_block_invoke + 277 (XXXLog.m:277)
4 FBLPromises 0x5138 __56-[FBLPromise chainOnQueue:chainedFulfill:chainedReject:]_block_invoke.18 + 52
5 libdispatch.dylib 0x63094 _dispatch_call_block_and_release + 24
6 libdispatch.dylib 0x64094 _dispatch_client_callout + 16
7 libdispatch.dylib 0x6924 _dispatch_queue_override_invoke + 924
8 libdispatch.dylib 0x13b94 _dispatch_root_queue_drain + 340
9 libdispatch.dylib 0x1439c _dispatch_worker_thread2 + 172
10 libsystem_pthread.dylib 0x1dc4 _pthread_wqthread + 224
11 libsystem_pthread.dylib 0x192c start_wqthread + 8
If I set the capacity of the disk cache to less than 5MB, It doesn't work.
Through the print statement, I checked that the value of the currentDiskUsage did not rise at all, and I also checked that the image has been making network requests every time because there is no cached data even if I shut down and run the app again. I'm simply wondering why this is happening.
Also, I wonder what kind of eviction policy the disk cache follows.
I was so curious that I tried to find out through the link [here], but there seems to be no implementation of disk cache at all.
Below is the code I used. I'm attaching it together just in case.
import UIKit
protocol Cacheable {
func getCachedResponse(
for path: String,
completion: @escaping (Result<Data, CacheError>) -> Void
)
func save(
for path: String,
data: Data
)
}
final class CacheManager {
static let shared = CacheManager()
private let imageCache: URLCache
init() {
imageCache = URLCache(
memoryCapacity: 4 * 1024 * 1024, // 4MB
diskCapacity: 4 * 1024 * 1024 // 4MB
)
}
}
extension CacheManager: Cacheable {
func getCachedResponse(
for path: String,
completion: @escaping (Result<Data, CacheError>) -> Void
) {
if let url = URL(string: path),
let cachedResponse = imageCache.cachedResponse(for: URLRequest(url: url)) {
completion(.success(cachedResponse.data))
return
}
completion(.failure(.noCachedResponse))
}
func save(
for path: String,
data: Data
) {
guard let url = URL(string: path) else { return }
let response = URLResponse(
url: url,
mimeType: nil,
expectedContentLength: 0,
textEncodingName: nil
)
if let uiImage = UIImage(data: data),
let compressedData = uiImage.jpegData(compressionQuality: 0.8) {
#if DEBUG
let formmatter = ByteCountFormatter()
formmatter.allowedUnits = [.useMB]
formmatter.countStyle = .file
print("""
=== Original size: \(formmatter.string(fromByteCount: Int64(data.count)))
=== Cached size: \(formmatter.string(fromByteCount: Int64(compressedData.count)))
""")
#endif
let cachedResponse = CachedURLResponse(
response: response,
data: compressedData
)
imageCache.storeCachedResponse(
cachedResponse,
for: URLRequest(url: url)
)
}
}
}
URLSession.shared.downloadTask doesn't work apple watch. I monitored network traffic but it doesn't. have any activity. Data(contentsOf: URL(string: url)!) works perfectly. Also, it works perfectly in preview. What do i do? Ask for more context if necessary.
I have an app with which users take photos and upload them in batches. It's used often on older devices, in areas with less than ideal network, and for durations of a full workday - so often the device has low power.
The current implementation of uploads uses an NSURLSession configured for the foreground, and as a result my users are used to having to keep the app in the foreground while an upload completes. However, these uploads are big and connectivity is often low, so this takes a long time - often users are stuck waiting with the app foregrounded for 15 minutes or so while the upload completes.
So, I created a build which uses an NSURLSession configured for the background. In the ideal case, users could start the upload, put the device in their pocket and continue their workday, and the next time they open their device it will be complete.
For some users this ideal case has come true. However, for others, the uploads sit in progress for an indeterminate amount of time, making no progress. My suspicion is that this is because the OS is deferring them until a time when network and power is more available. However, my users are using work devices at a work location - reliable power and network might never be available. Being able to background the app and continue working is valuable for these users, but having the upload complete promptly is essential for them.
My questions are:
Is it true that background configured NSURLSessions will defer network requests when connectivity or power is low, even if discretionary = NO? Is the exact behavior for when requests will be attempted in the background documented?
Is there a way to reliably test background configured NSURLSessions in XCode? I've attempted throttling my connection with Charles Proxy, and using my device in Low Power Mode, but I'm unable to reproduce the request stalling behavior my users are experiencing in the wild.
Is there a way to create an NSURLSession that will muscle through difficult or inefficient uploads in the background, with the same reliability as a foreground session?
If not, what is Apple's recommended approach to situations like mine? I've considered queueing both a background and foreground upload, and cancelling the other once one completes, but this seems disrespectful to the user's resources.
Will setting timeoutIntervalForResource to a lower value cause the OS to more aggressively attempt uploads? Or simply to throw an error sooner? I want the OS to give the upload a long time to complete, but I also want it to attempt it right away.
Thanks for any information!