CFNetwork

RSS for tag

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

Posts under CFNetwork tag

106 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Networking Resources
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"
0
0
2.2k
Feb ’24
TCP Fast Open in URLSession
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)
1
0
114
1w
How to set NWProtocolTLS handshake as server or client manually
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 } }
5
0
264
2w
NSURL CFNetwork Crashed in iOS18 Beta
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
2
0
226
Jun ’24
Error when downloading files with multiple background urlsession
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
3
9
368
Jun ’24
app crashed on launch
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!
3
0
286
Jun ’24
CFNetwork crash
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)
1
0
173
Jun ’24
CFNetwork Exception Issue Impacting Large Number of Users, Primarily on iOS 17
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!"
10
0
345
Jun ’24
CFNetwork Exception Issue Impacting Large Number of Users, Primarily on iOS17
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!"
3
0
223
Jun ’24
Sometime Crash CFNetwork CFURLRequestSetHTTPRequestBody + 36
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
4
0
283
Jun ’24
What kind of eviction policy the disk Cache follows and it does not work when it is less than 5 MB
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) ) } } }
1
0
313
May ’24
Background NSURLSession when uploads must be prompt
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!
1
0
318
May ’24
TLS client certificate
I have a customer who wants to protect the REST API of their app with a private certificate. They would then distribute the client certificate to the authorized users. Their app would not work unless the client certificate is already installed on the user's phone before they run the app. I have never done this before. Is it possible to install a client certificate on an iPhone without running an app, for example if it were sent in an email message? And if it is possible, is App Review going to let such an app into the app store? Thanks, Frank
1
0
406
Apr ’24
Need Help For Setting Up HTTPS
Hi I Download my app from test flight, when i click submit button to a backend call. App expects to get back with the response from the backend, to take to next pages. But the app seems to be stuck waiting for the backend response. No error messages seen. i am sure the backend call is blocked from the test flight version. Same code works well from emulator and the physical device from local and from Google PlayStore. Only the test flight is the problem. I am sure i messed up some settings , My Info.plist has as in below, can anyone please help. NSAppTransportSecurity NSPinnedNetworkSecurityItems MyBundleName NSIncludesSubdomains NSAllowsArbitraryLoads NSPinnedCAIdentities SPKI-SHA256-BASE64 THEKEY
1
0
382
Apr ’24
Announcer for proxy host/port updates?
Hello, I have some networking code that checks whether a proxy is configured via: `CFStringRef host = (CFStringRef)CFDictionaryGetValue(globalSettings, kCFNetworkProxiesHTTPProxy);` `CFNumberRef port = (CFNumberRef)CFDictionaryGetValue(globalSettings, kCFNetworkProxiesHTTPPort);` I need to do this fairly frequently, so I am wondering if there is an announcer I can subscribe to instead?
4
0
428
Apr ’24
Dispatch queue: com.apple.NSURLSession-delegate after executing self written shortcut
Currently I am trying to create some shortcuts for my iOS 17 app. The AppIntent looks like this: class PostClass{ public init() { let url = URL(string: "http://myurl")! var request = URLRequest(url: url) request.httpMethod = "POST" struct Message: Encodable { let device_type: String } let message = Message( device_type: "device" ) let data = try! JSONEncoder().encode(message) request.httpBody = data request.setValue( "application/json", forHTTPHeaderField: "Content-Type" ) self.request = request } } var activateDevice = PostClass() @available(iOS 17, *) struct ActivateIntent: AppIntent { static let title: LocalizedStringResource = "Activate" func perform() async throws -> some IntentResult { let task = URLSession.shared.dataTask(with: activateDevice.request) { data, response, error in let statusCode = (response as! HTTPURLResponse).statusCode if statusCode == 200 { print("SUCCESS") } else { print("FAILURE") } } task.resume() return .result() } } Unfortunately, the shortcut throws an error after every second execution. I looked into the ips-file and saw the following traceback: Thread 2 Crashed: 0 Runner 0x1028ddd30 closure #1 in ActivateIntent.perform() + 388 1 CFNetwork 0x1a6f39248 0x1a6f2a000 + 62024 2 CFNetwork 0x1a6f57210 0x1a6f2a000 + 184848 3 libdispatch.dylib 0x1adced13c _dispatch_call_block_and_release + 32 4 libdispatch.dylib 0x1adceedd4 _dispatch_client_callout + 20 5 libdispatch.dylib 0x1adcf6400 _dispatch_lane_serial_drain + 748 6 libdispatch.dylib 0x1adcf6f64 _dispatch_lane_invoke + 432 7 libdispatch.dylib 0x1add01cb4 _dispatch_root_queue_drain_deferred_wlh + 288 8 libdispatch.dylib 0x1add01528 _dispatch_workloop_worker_thread + 404 9 libsystem_pthread.dylib 0x201dd4f20 _pthread_wqthread + 288 10 libsystem_pthread.dylib 0x201dd4fc0 start_wqthread + 8 Is there any way to locate the error with these information? Has it something to do with the fact that my code is not thread-safe? Or is there any internal bug? Grateful for any help, thanks in advance!
5
0
533
Apr ’24