CFNetwork

RSS for tag

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

CFNetwork Documentation

Pinned Posts

Posts under CFNetwork tag

128 Posts
Sort by:
Post not yet marked as solved
3 Replies
440 Views
Hi There, I am trying to record a meeting and upload it to AWS server. The recording is in .m4a format and the upload request is a URLSession request. The following code works perfectly for recordings less than 15 mins. But then for greater recordings, it gets stuck Could you please help me out in this? func startRecording() { let audioURL = getAudioURL() let audioSettings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { audioRecorder = try AVAudioRecorder(url: audioURL, settings: audioSettings) audioRecorder.delegate = self audioRecorder.record() } catch { finishRecording(success: false) } } func uploadRecordedAudio{ let _ = videoURL.startAccessingSecurityScopedResource() let input = UploadVideoInput(signedUrl: signedUrlResponse, videoUrl: videoURL, fileExtension: "m4a") self.fileExtension = "m4a" uploadService.uploadFile(videoUrl: videoURL, input: input) videoURL.stopAccessingSecurityScopedResource() } func uploadFileWithMultipart(endPoint: UploadEndpoint) { var urlRequest: URLRequest urlRequest = endPoint.urlRequest uploadTask = URLSession.shared.uploadTask(withStreamedRequest: urlRequest) uploadTask?.delegate = self uploadTask?.resume() }
Posted
by snehal-a.
Last updated
.
Post not yet marked as solved
1 Replies
2.5k Views
This post is part of the Local Network Privacy FAQ - https://developer.apple.com/forums/thread/663858. My app presents the local network privacy alert unexpectedly. Is there a way to track down the cause? If the alert is correlated with something you do in your app then you can step through your code to see what triggers it. However, in some cases this won’t help. For example, some third-party libraries automatically run code in your app that triggers the local network privacy alert. One option here is to start removing any third-party libraries from your app until you figure out which one is triggering it, and then raise this issue with the library’s vendor. If you get completely stuck then start a new thread here on DevForums - https://developer.apple.com/forums/ and I’ll try to help out there. Make sure to tag your thread with one of the standard networking tags (Bonjour, CFNetwork, or Network). Back to the FAQ - https://developer.apple.com/forums/thread/663858
Posted
by eskimo.
Last updated
.
Post not yet marked as solved
3 Replies
1.3k Views
I'm trying to set up background HTTP upload requests (syncing files from the user's phone to a server) that trigger periodically in my Swift app. I don't have strict requirements on when this runs (it can happen overnight or throughout the day). I know Apple provides several APIs for background tasks on iOS (beginBackgroundTask, BGAppRefreshTaskRequest, BGProcessingTaskRequest, URLSession upload vs. background session). And I've seen this post on the Apple developer forums that attempts to explain the differences and when to use which - as well as Apple's page on the subject, but it's still not clear to me how a few of these work in practice, and thus which ones I should utilize for my use case. My questions: How should I schedule periodic file upload tasks in the background? I assume I should use BGProcessingTaskRequest, since I don't know exactly how long the task will take (it could be syncing just 1-2 files, or it could be hundreds) and I don't care if it runs overnight How should I ensure foreground tasks are able to complete after closing the app? (i.e. when a user starts a sync manually in the app) From Apple's page on URLSessionUploadTask: "Unlike data tasks, you can use upload tasks to upload content in the background." Does this mean any requests I make using URLSession.shared.upload() will automatically run in the background if the user closes the app? Even with the async/await version, or do I have to use the completionHandler version? Do I need to call beginBackgroundTask if I'm using URLSession.shared.upload() to guarantee I get more time to finish uploads? What about sequential requests (i.e. requests that haven't started yet by the time the app is closed)? Based on this StackOverflow response, it sounds like I may need to trigger all the uploads in parallel beforehand? https://stackoverflow.com/a/53949607/2359478 Should I even consider URLSessionConfiguration.background for my use case? It sounds like it I use beginBackgroundTask and BGProcessingTaskRequest then this may be unnecessary? Thanks!
Posted Last updated
.
Post not yet marked as solved
2 Replies
508 Views
Hello, I am having an issue with my request response only containing a partial response body despite the request having a 200 http response status. When I print out the raw response without parsing it to JSON I can see that the content is truncated (leading to an invalid JSON). I am unable to reproduce the same issue on Postman, so this seems to be isolated to my ios app (I have had the same issue with the endpoint in React Native as well). Any tips or suggestions would be appreciated! (Excuse the code, learning swift as I go) class Fetcher<T, G>: ObservableObject where T: Decodable, G: Codable { @Published var data: T? = nil @Published var isLoading: Bool = false public var path: [String] { return [] } func fetchData(body: G) async throws { Task { @MainActor in isLoading = true } var url = NetworkManager.shared.baseUrl; for p in path { url = url.appending(path: p) } var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try? JSONEncoder().encode(body) // TODO: This should be handled with auth challenges if let token = NetworkManager.shared.token { request.setValue(token, forHTTPHeaderField: "Authorization"); } // Set timezone header request.setValue(TimeZone.current.identifier, forHTTPHeaderField: "TIMEZONE"); let (respData, response) = try await NetworkManager.shared.session.data(for: request) let json = String(data: respData, encoding: String.Encoding.utf8) if let token = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Authorization") { NetworkManager.shared.token = token } guard (response as? HTTPURLResponse)?.statusCode == 200 else { Task { @MainActor in isLoading = false } throw FetchError.badRequest } let temp = try JSONDecoder().decode(T.self, from: respData) Task { @MainActor in data = temp isLoading = false } } } class NetworkManager{ static let shared = NetworkManager(baseUrl: "https://my-api-url.com"); let baseUrl: URL let session: URLSession var token: String? private init(baseUrl: String) { // TODO: Throw well defined error self.baseUrl = URL(string: baseUrl)! let configuration = URLSessionConfiguration.default self.session = URLSession(configuration: configuration) } }
Posted Last updated
.
Post not yet marked as solved
1 Replies
462 Views
I would like to call a "GetMessages" API every 10 minutes while the app is not active or shutdown. if a message is returned, display the message as a local notification Will the background api run if the app is shut down? An example of this is when an email app shows a notification. Can they pull from their server while the app is not running or do they use the push notification service. I know that calendar events can be scheduled locally and for location changes, but I don't know if calling a api task with the app not running is possible.
Posted Last updated
.
Post not yet marked as solved
8 Replies
937 Views
We are an SDK manufacturer, providing our clients with an HTTP network proxy SDK. Recently on iOS 17.1.1 version, a problem was encountered. After the proxy is started, the system is prone to crash, which looks like a crash in the iOS network library. The crash information is as follows: In other versions of iOS (15, 16) etc., I would like to ask whether the cause of the crash can be seen from the information provided? Is it an issue on our side, or a BUG in the iOS system?
Posted Last updated
.
Post not yet marked as solved
9 Replies
3.8k Views
I have received two strange crash reports from an iPad11,7 running iPadOS 15.1 and an iPad11,2 running iPadOS 15.2. On both occasions, the crashed thread calls CFURLRequestSetMainDocumentURL, which in turn calls _dispatch_source_set_runloop_timer_4CF in libdispatch, after which the application crashes with SIGSEGV and SEGV_MAPERR. The crashed thread's call stack is displayed below. Full crash logs are attached as well. What could this be? Exception Type: SIGSEGV Exception Codes: SEGV_MAPERR at 0x21d Crashed Thread: 20 Thread 20 Crashed: 0 libdispatch.dylib 0x00000001829e1784 _dispatch_source_set_runloop_timer_4CF + 36 1 CFNetwork 0x00000001834fc824 CFURLRequestSetMainDocumentURL + 2240 2 CFNetwork 0x00000001836b89a8 _CFNetworkErrorGetLocalizedDescription + 693652 3 CFNetwork 0x00000001834fdb1c CFURLRequestSetMainDocumentURL + 7096 4 CFNetwork 0x00000001834f3c34 CFURLRequestSetURL + 9668 5 libdispatch.dylib 0x00000001829ca914 _dispatch_call_block_and_release + 28 6 libdispatch.dylib 0x00000001829cc660 _dispatch_client_callout + 16 7 libdispatch.dylib 0x00000001829d3de4 _dispatch_lane_serial_drain + 668 8 libdispatch.dylib 0x00000001829d498c _dispatch_lane_invoke + 440 9 libdispatch.dylib 0x00000001829d5c74 _dispatch_workloop_invoke + 1792 10 libdispatch.dylib 0x00000001829df1a8 _dispatch_workloop_worker_thread + 652 11 libsystem_pthread.dylib 0x00000001f1eea0f4 _pthread_wqthread + 284 12 libsystem_pthread.dylib 0x00000001f1ee9e94 start_wqthread + 4 second_crashlog.txt report-2517628380750009999-e4d7ea06-6f22-4b7e-b129-045599e1dee5.txt
Posted
by datwelk.
Last updated
.
Post not yet marked as solved
2 Replies
572 Views
Hi, I've recently noticed some crash started to happening around CFNetwork and looking at the crash log I was unable to determine the cause of the crash and not sure if anyone else have a similar experience? This seem to happen more frequently on iOS 17 than iOS 16? I'm unable to reproduce myself but I've managed to get an Apple crash report for both iOS 16 and 17. Any help is much appreciated. iOS 16.crash iOS 17.crash
Posted
by YK_LS.
Last updated
.
Post not yet marked as solved
1 Replies
527 Views
I am developing a cloud-based application and have integrated the FileProviderExtension. However, files larger than 20 MB are not downloading as it’s throwing a memory limit exception. In this process I have downloaded the file data but after downloaded data need to decompression the data . I am getting memory limit exception during decompression. I am using below file to decompress the data. let decompressedData = try? decryptedChunkBytes?.gunzipped() Data+Gzip.swift
Posted Last updated
.
Post marked as solved
2 Replies
509 Views
I'm trying to download a small data file using NSURLSession, but the completion handler is never called (where "never" means I waited long after the specified timeout). NSURLSessionConfiguration* config = NSURLSessionConfiguration.ephemeralSessionConfiguration; config.timeoutIntervalForResource = 120.0; config.timeoutIntervalForRequest = 120.0; NSURLSession* session = [NSURLSession sessionWithConfiguration: config]; [session dataTaskWithURL: inURL completionHandler: ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { ... }]; I'm trying to update some old code that used the deprecated NSURLConnection class, and am using the same URL, so I know that the URL is good.
Posted
by JWWalker.
Last updated
.
Post marked as solved
1 Replies
390 Views
I was testing bytes(from:delegate:) API from URLSession. I was testing the implementation of the delegate. I didn't get any callback to the delegate when I got 400 status code in the response(No token is provided). I have implemented other delegates also. Still I didn't get any callback in any of those functions. Please let me know if I am missing something here?
Posted
by VVD93.
Last updated
.
Post not yet marked as solved
4 Replies
982 Views
memory leak in when working with URLSession webSocketTask introductory command line app, mac os Ventura 13.2.1 the first leak is fixed on the URLSessionWebSocketDelegate delegate func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) further when calling receive closures or through func receive() async throws -> URLSessionWebSocketTask.Message the system is constantly leaking memory In order to understand how sad everything is, I recommend opening 20-50 sockets in parallel for large data streams, as an example, financial exchanges per day of work, 0.2-1 gigabytes of leakage will accumulate there is one suggestion, maybe it will help fix the bug, it is connected with another leak in the system that appears in the absence of user interactions, example if we create 20-50 swiftUI labels and start updating them fast enough 5-10 times per second and stop interacting with the mouse, keyboard and touchbar, we will get a memory leak when the old label data is not destroyed by the system - and without touching the keyboard, the mouse in an hour several gigabytes will leak us, then if you move the mouse or press a button on the keyboard, the system will clear the memory
Posted
by Druidvfx.
Last updated
.
Post not yet marked as solved
3 Replies
937 Views
Hello, For our iOS app, we're switching WebSocket client implementation from one using Poco project - https://github.com/pocoproject/poco to one based on NSURLSessionWebSocketTask. We are observing one regression which prevents us from shipping this solution though: 5-7% of calls to -[NSURLSessionWebSocketTask cancelWithCloseCode:reason:] fail to deliver given close code to server and 1006 close code (AbnormalClosure) is used instead. Our test consist of following steps: Create WebSocket using NSURLSessionWebSocketTask Send "Hello" message Close WebSocket with 1011 close code Destroy NSURLSessionWebSocketTask instance Check whether server received 1011 close code We do not perform those steps line by line, but rather use delays (~100-200ms) between each step. We perform such test 1000 times and observe 5-7% failure rate consistently. Distribution of failures is random. We did perform test on both iOS simulator and iOS devices with no observable differences. We did perform test on multiple server implementations (tornado- and node.js based ones) running on local machine (same as Xcode) and remote one We always receive "Hello" message on server 1011 close code is arbitrarily chosen for testing, but results are same for different ones, too. We did setup mitmproxy and for failed tests see following log: Error in WebSocket connection to 20.16.12.131:8080: WebSocket connection closed unexpectedly by client: TcpDisconnect(None) We did enable CFNetwork diagnostic using CFNETWORK_DIAGNOSTICS and found one difference between success and failure cases. For successful cases we see log which looks like this: default 16:27:15.831193+0200 Playground-ObjC tcp_close [C7.1:2] TCP Packets: snd 0.000s seq 1092086878:1092086879 ack 0 win 65535 len 0 [SEC] rcv 0.004s seq 3101059099:3101059100 ack 1092086879 win 65535 len 0 [S.] snd 0.000s seq 1092086879:1092086879 ack 3101059100 win 4117 len 0 [.] snd 0.002s seq 1092086879:1092087279 ack 3101059100 win 4117 len 400 [P.] rcv 0.001s seq 3101059100:3101059100 ack 1092086879 win 2058 len 0 [.] rcv 0.000s seq 3101059100:3101059100 ack 1092087279 win 2052 len 0 [.] rcv 0.015s seq 3101059100:3101059229 ack 1092087279 win 2052 len 129 [P.] ECT0 snd 0.000s seq 1092087279:1092087279 ack 3101059229 win 4113 len 0 [.] snd 0.003s seq 1092087279:1092087289 ack 3101059229 win 4113 len 10 [P.] rcv 0.002s seq 3101059229:3101059229 ack 1092087289 win 2052 len 0 [.] snd 0.017s seq 1092087289:1092087297 ack 3101059229 win 4113 len 8 [P.] snd 0.001s seq 1092087297:1092087298 ack 3101059229 win 4113 len 0 [F.] rcv 0.000s seq 3101059229:3101059229 ack 1092087297 win 2052 len 0 [.] rcv 0.001s seq 3101059229:3101059233 ack 1092087297 win 2052 len 4 [P.] ECT0 Last packet 0ms ago. So it's something related to "tcp_close" and seems to log whole TCP packets that were exchanged during connection. For failed cases such log is not present. One additional log we see potentially interesting (but were not able to confirm its meaning or relation to failed cases) comes from runningboardd: default 16:27:15.830447+0200 runningboardd Invalidating assertion 33-1364-23682 (target:[applicationorg.example.app:1364]) from originator [applicationorg.example.app:1364] So that's where we are right now and we have no idea where to dig next. We wonder if anyone else have seen such problem or can point us to any direction we could try next. Thanks much, Damian & Maciek
Posted
by kurak.
Last updated
.
Post not yet marked as solved
0 Replies
15k Views
I regularly get asked questions about local network privacy. This is my attempt to collect together the answers for the benefit of all. Before you delve into the details, familiarise yourself with the basics by watching WWDC 2020 Session 10110 Support local network privacy in your app. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Local Network Privacy FAQ With local network privacy, any app that wants to interact with devices on your network must ask for permission the first time that it attempts that access. Local network privacy is implemented on iOS, iPadOS, and the current visionOS beta. It’s not implemented on other platforms, including macOS and tvOS. Some common questions about local network privacy are: FAQ-1 What is a local network? FAQ-2 What operations require local network access? FAQ-3 What operations require the multicast entitlement? FAQ-4 Do I need the multicast entitlement? FAQ-5 I’ve been granted the multicast entitlement; how do I enable it? FAQ-6 Can App Clips access the local network? FAQ-7 How does local network privacy work with app extensions? FAQ-8 How do I explicitly trigger the local network privacy alert? FAQ-9 How do I tell whether I’ve been granted local network access? FAQ-10 How do I use the unsatisfied reason property? FAQ-11 Do I need a local network usage description property? FAQ-12 Can I test on the simulator? FAQ-13 Once my app has displayed the local network privacy alert, how can I reset its state so that it shows again? FAQ-14 How do I map my Multipeer Connectivity service type to an entry in the Bonjour services property? FAQ-15 My app presents the local network privacy alert unexpectedly. Is there a way to track down the cause? FAQ-16 On a small fraction of devices my app fails to present the local network privacy alert. What’s going on? FAQ-17 Why does local network privacy get confused when I install two variants of my app? FAQ-18 Can my app trigger the local network privacy alert when the device is on WWAN? Revision History 2023-10-31 Fixed a bug in the top-level FAQ that mistakenly removed some recent changes. Added FAQ-18. 2023-10-19 Added a preamble to clarify that local network privacy is only relevant on specific platforms. 2023-09-14 Added FAQ-17. 2023-08-29 Added FAQ-16. 2023-03-13 Added connecting a UDP socket to FAQ-2. 2022-10-04 Added screen shots to FAQ-11. 2022-09-22 Fixed the pointer from FAQ-9 to FAQ-10. 2022-09-19 Updated FAQ-3 to cover iOS 16 changes. Made other minor editorial changes. 2020-11-12 Made a minor tweak to FAQ-9. 2020-10-17 Added FAQ-15. Added a second suggestion to FAQ-13. 2020-10-16 First posted.
Posted
by eskimo.
Last updated
.
Post not yet marked as solved
0 Replies
367 Views
This post is part of the Local Network Privacy FAQ. Can my app trigger the local network privacy alert when the device is on WWAN? Yes. While the local network privacy alert is most commonly seen when the device is on a Wi-Fi network, that’s not required. It’s possible for your app to trigger the local network privacy alert on a device that is on WWAN. Indeed, the alert can show up even if you: Leave the current Wi-Fi network in Control Center Turn Wi-Fi off in Settings Enable Airplane Mode in Settings Back to the FAQ
Posted
by eskimo.
Last updated
.
Post not yet marked as solved
1 Replies
591 Views
I have a project that must upload data in background and keep data going even when the app is closed/terminated. So i have a background upload of data that should start/continue when the app is unloaded from memory (user force exit). In most of the cases after killing the app background upload resumes after some time (from few seconds to 10-20 mins) and data is successfully sent. However this does not always work even as expected. When the user kills the application, background uploading may terminate too with an error «Error Domain=NSURLErrorDomain Code=-999 "(null)" UserInfo={NSURLErrorBackgroundTaskCancelledReasonKey=0» After killing the app background upload may stop without finishing/throwing error and never produce any event, and when I open the application background upload does not resume. There is no error events and there is no pending/active background tasks either on my URLSession. Can they really vanish this way? In very rare cases I have encountered the problem that when background uploading in proccess (app is fully closed and when I launch the application a white screen appears (i see no splash screen, no main view), but I still can see logs that the background tasks is working actively. After the completion of data uploading the white screen does not go away, it is necessary to re-launcth the application to solve this problem. I note that these cases are not always encountered and most of the time background upload works correctly. But I'd would like to understand how to handle these problems and what can cause this weirdness. Do I get that right, so that after the user has force exited the application and it is unloaded from memory, even if a background upload task is launhed - we have no guarantee that the task will complete and the system won't kill the background task? I guess i have to act on my own, keep an eye on my tasks and restart them if they're got vanished/terminated? Is there any advices or good practices how to handle this best? And are there any strict limits on the amount of data that can be sent in background per task? P.S I do have these capabilities enabled: Background fetch & Background processing.
Posted
by ElissP.
Last updated
.
Post not yet marked as solved
1 Replies
377 Views
We've noticed that network requests triggered when a user interacts with our widget are very unreliable. In development, they almost always work, but in production, many of them never reach the server, especially when many requests are performed in a row. The requests are performed using the URLSession.shared singleton instance: let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in ... } task.resume() Are there any limitations or restrictions on Interactive Widgets in a production environment that might cause this behavior? Is there a different way to implement or configure widgets to ensure network requests are reliably performed? Thank you.
Posted Last updated
.
Post marked as solved
4 Replies
671 Views
I am developing a cloud-based application and have integrated the FileProviderExtension. However, files larger than 20 MB are not uploading, as it's throwing a memory limit exception. Error: Thread 28: EXC_RESOURCE (RESOURCE_TYPE_MEMORY: high watermark memory limit exceeded) (limit=20 MB)
Posted Last updated
.