Network connections send and receive data using transport and security protocols.

Posts under Network tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

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
338
3w
Unwanted Communication Reporting Extension - error with classificationreport url
Hi, I'm having headaches with the debugging of my Unwanted Communication Reporting extension. iPhone log says: com.apple.IdentityLookup.MessageFilter[1774] <Error>: Extension's containing app (appID <private>) unauthorized to defer requests to host <private> So I guess I have something wrong with my apple-app-site-association. The AASA file I get with swcutil dl -d services.mydomain.com { classificationreport = { apps = ( "<MYTEAMID>.com.mydomain.myapp", "<MYTEAMID>.com.mydomain.myapp.unwanted" ); }; } where .com.mydomain.myapp is my containing app (bundle id). and .com.mydomain.myapp.unwanted is my extension The AASA file on the server is obviously in JSON format and correctly served from the server : services.mydomain.com In the extension Info.plist I've set the following : <key>NSExtension</key> <dict> <key>NSExtensionAttributes</key> <dict> <key>ILClassificationExtensionNetworkReportDestination</key> <string>https://services.mydomain.com/path/unwanted/report</string> </dict> <key>NSExtensionMainStoryboard</key> <string>MainInterface</string> <key>NSExtensionPointIdentifier</key> <string>com.apple.identitylookup.classification-ui</string> </dict> I suppose the reply from classificationResponse method is correct since MessageFilter "tries" to send the request. Where am I mistakening ? Difficult to debug... MessageFilter's log keeps interesting data as private (so there is no way to check what it's actually doing). And I've found no way to go deeper in the debug process. Many thanks Emmanuel
2
0
243
4w
iOS App udp and local network permission
Recently, my application was having trouble sending udp messages after it was reinstalled. The cause of the problem was initially that I did not grant local network permissions when I reinstalled, I was aware of the problem, so udp worked fine after I granted permissions. However, the next time I repeat the previous operation, I also do not grant local network permissions, and then turn it back on in the Settings, and udp does not work properly (no messages can be sent, the system version and code have not changed). Fortunately, udp worked after rebooting the phone, and more importantly, I was able to repeat the problem many times. So I want to know if the process between when I re-uninstall the app and deny local network permissions, and when I turn it back on in Settings, is that permissions have been granted normally, and not fake, and not required a reboot to reset something for udp to take effect. I'm not sure if it's the system, or if it's a similar situation as described here, hopefully that will help me find out
4
1
277
4w
Network framework and background tasks
Hi team, I'm working on an MQTT client for Apple platforms (macOS, iOS, and possibly tvOS and watchOS). I would like the client to listen to messages even when the application is in the background. I would appreciate any suggestions on the best approach to achieve this. Based on iOS Background Execution Limits, it seems that my best bet is to use a long-running background process with BGProcessingTaskRequest while setting up the connection. Does that sound like the right approach? Is there any limits for the bg tasks? I currently have a working BSD socket. I'm not sure if it is necessary to switch to the Network Framework to have the background task working, but I'm open to switching if it's necessary. If the approach works, does that mean I could built a http client to process large upload/download tasks without using NSURLSession? As I'm working on a cross platform project, it would be benefit if I dont need a separate http client implementation for Apple. Any insights on this topic would be greatly appreciated. Additionally, it's off topic, but the link to "WWDC 2020 Session 10063 Background Execution Demystified" (https://developer.apple.com/videos/play/wwdc2020/10063/) is broken. Is there a way to access the content there? Thanks in advance for your help and insights!
3
0
210
4w
How to determine that NWBrowser has finished?
I am using NWBrowser to detect SignalK servers on a network using the following Swift code: let browser = NWBrowser(for: .bonjourWithTXTRecord(type: "_http._tcp", domain: nil), using: NWParameters()) browser.browseResultsChangedHandler = { results, changes in print("Found \(results.count) results and \(changes.count) changes") } When this is run on a network with 5 devices then the output is often Found 5 results and 5 changes But, sometime it is: Found 2 results and 2 changes Found 5 results and 3 changes indicating that the browseResultsChangedHandler is being called more than once. So my question is how do I determine when the browsing process has finished (obviously without the knowledge that there are 5 devices)? The depreciated NetServiceBrowser had a delegate method (netServiceBrowser(_:didFind:moreComing:) but I can't see an equivalent for NWBrowser. The only method I can think of is to apply a short time out.
3
0
217
4w
Wake Up iPad from sleep into single app mode by BLE and Network
Hi, we actually have an application where we use iPad to run a WEB Application to display multiple Entertainment/Information content and control Infrastructure. The device is usually connected to a base station (own design) using BLE und USB only for power, is locked in single App Mode using MDM. As long as the App is open it is working fine. But now we like to go to the next step and like to have the device movable and use power save. How can we achieve the iPad wakes up immediately from sleep mode (directly to the app) if somebody is pressing a button on the base station (we support Comm Port, and HID Keyboard service, we can change code on base station if needed). And how can we achieve the same over Network (Wi-Fi or Ethernet with Adapter, Internet access is not always available). May set a state on the MQTT broker and tablet should wake up from sleep. Thanks for feedback Patrik
3
0
230
Jun ’24
Private Access Tokens versus App Attest + DeviceCheck -- which one should I use to protect my app?
Private Access Tokens (PATs) are headlined as something that can eliminate CAPTCHAs, but also includes app-to-server communications in its use cases. Because of this, they seem to perform a very similar function to DeviceCheck, since both aim to attest to the health of the device in question. I don't really understand the difference between the two and find this confusing. Since PATs are newer and more general, I'm more inclined to adopt them, but where does this leave DeviceCheck? Is it redundant? How does App Attest fit into all of this? If my goal is to minimize if not eliminiate fraudulent/malicious use of my app's APIs, should I use Private Access Tokens, DeviceCheck, and App Attest simultaneously to maximize my protection? If not, what is accepted to be the best practice? I admire Apple's dedication to privacy and security, but as a new developer I feel Apple could make it easier for their app developers to find out and implement the latest best practices.
1
0
293
Jun ’24
QUIC Connection Group Server Sending Pace
We have an implementation in which we use QUIC via a connection group, server are client are on Swift using the Network framework. Our use case is, the server should send data buffers to the client as fast and as much as possible, now the pace to call the send method from the server should be carefully done, because if we send too much data of course the client is not gonna be able to receive it. The question would be, is there a way to query the congestion window so we know on the server side, how much data we should be able to send at some point? Asking because we are not getting all the data we are sending from the server on our client side... We are using these settings: let options = NWProtocolQUIC.Options(alpn: ["h3"]) options.direction = .bidirectional // options.idleTimeout = 86_400_000 options.maxUDPPayloadSize = Int.max options.initialMaxData = Int.max options.initialMaxStreamDataBidirectionalLocal = Int.max options.initialMaxStreamDataBidirectionalRemote = Int.max options.initialMaxStreamDataUnidirectional = Int.max options.initialMaxStreamsBidirectional = 400 options.initialMaxStreamsUnidirectional = 400 Questions: 1.- Can we get a little more detail in above options, specifically on their impact to the actual connection? 2.- IsinitialMaxData the actual congestion window value 3.- Are we missing something or making incorrect assumptions? Thanks in advance.
10
0
316
1w
FilterPacketProvider and outgoing bandwidth dramatically decrease in 10Gbit networks
Hello, For several versions, we have had a NetworkExtension registered to "FilterDataProvider" for content filtering reasons, with no issues about performance in 10Gigabit networks. In our latest version, we added registration to "FilterPacketProvider" for packet filtering purposes, and from that moment, we have observed that outgoing bandwidth dramatically decreases by 90% (from 883 MB/s to 140MB/s), simply due to being registered to "FilterPacketProvider," without any processing by us, just only registering and returning ALLOW: class FilterPacketProvider: { override func startFilter(completionHandler: @escaping (Error?) -> Void) { self.packetHandler = {(_pContext: NEFilterPacketContext, _pIface: OS_nw_interface, _pDirection: NETrafficDirection, _pRawData: UnsafeRawPointer, _pRawDataLength: Int) -> NEFilterPacketProvider.Verdict in return self.handleNewPacket(context: _pContext, interface: _pIface, direction: _pDirection, rawData: _pRawData, rawDataLength: _pRawDataLength) } }} func handleNewPacket(context: NEFilterPacketContext, interface: OS_nw_interface, direction: NETrafficDirection, rawData: UnsafeRawPointer, rawDataLength: Int) -> NEFilterPacketProvider.Verdict { return .allow } The most curious thing is that this behaviour only happens with outgoing traffic, while incoming traffic does not experience any performance penalty. Reviewing similar cases, we found a similar post here: https://developer.apple.com/forums/thread/741965 So, our questions are: 1. Could we be doing something wrong when registering to NEFilterPacketProvider? 2. Is there still any known performance bug with outgoing traffic in NEFilterPacketProvider as I read in the post I found and attached? 3. If this bug is confirmed, is there any estimated date for its correction? Best regards, Asier Gil.
2
1
264
4w
A case against TN3135 WatchOS restrictions (NWPathMonitor)
REF: TN3135 Context: Stand alone watch app Target platform is cellular watch Phone likely (90%) out of range in a different location (although this applies equally to watch+phone too) User story: As a water & wind sports enthusiast who is either in-shore, near-shore or off-shore I want to receive near-real-time wind reports on my wrist so that I can determine ...(many varieties of facts) My Case for lifting restrictions on NWPathMonitor, NWPath, NWPath.Status What this is about: Proactive UX (enlightening) vs. Reactive UX (disappointing) Reducing unnecessary code execution proactively Exactly the same purpose the tiny red x at the top center of the Watch screen serves (notifies me that the watch is offline -- probably using NWPath.Status of .unsatisfied) What this is NOT about Preflighting requests UI design (although there is a UI component associated with UX - like the tiny red x ...) Establishing low level connections Watch App End User Scenario Water & Wind sports enthusiasts are frequently in and out of cellular range. As a kiteboarding enthusiast I am relating my personal experience. The phone is in the vehicle in the parking lot > 100 yards away while I'm standing on the beach (before I get into the water). On shore or just off shore my watch likely has a solid connection. When 100 yards off shore watch has a decently but tenuous connection. While at 200 yards off shore watch has no connection at all. Developer's Case Current REACTIVE solution My current watch app is forced to be reactive by attempting a URLSession request and capturing one of the plethora of URLError error conditions. This action, of course, is activated through a user interaction workflow: User interaction --> create URL --> use URLSession --> capture URLError --> determine failure cause --> notify user network data cannot be retrieved Optimal PROACTIVE solution Provide a simple indicator to the end user that the data cannot be retrieved. The reason is not relevant to the end user, but they know their interaction with the app is unnecessary. The app's UX has been improved by proactively precluding an unnecessary interaction and precluding unecessary code execution behind the scenes. NWPath.Status = .unsatisfied --> UI shows "no network" type indicator --> (no user interaction - no backend requests - no code execution) --> NWPath.Status = .satisfied --> UI shows nominal status --> end user interacts normally Rationale Using NWPath.Status allows us as developers to fulfill some basic tenets of the Human Interface Guidelines associated with Providing Feedback Specifically, the overview states we should communicate: The current status of something A warning about an action that can have negative consequences And quoting about my specific use case, the guidelines continue: ... it often works well to display status information in a passive way so that people can view it when they need it. Consider integrating status feedback into your interface. Show people when a command can’t be carried out and help them understand why. And finally, the guideline specifically calls out the WatchOS experience I am attempting to avoid. By proactively providing feedback we can prevent the reactive "touch --> wait & see --> then disappoint with no connection" approach. Final Thoughts I realize I am naive about the behind the scenes with this API. I realize that this is likely not the intended use of this API. But as a developer, I also realize users of our stuff often use it in ways we never intended. Please allow these API features on WatchOS
9
1
362
Jun ’24
Unix Domain Socket, Network Framework and App Sandboxing
Dear Apple Developers, I am working on a macOS project where the container app acts as a server and communicates with a command-line program developed by my colleagues via a Unix domain socket. The macOS part was written using the new Network Framework. Here is a snippet of the code: let params = NWParameters() let socketFile = URL(fileURLWithPath: socketPath) params.defaultProtocolStack.transportProtocol = NWProtocolTCP.Options() params.requiredLocalEndpoint = NWEndpoint.unix(path: socketFile.path) params.allowLocalEndpointReuse = true self.listener = try! NWListener(using: params) listener?.newConnectionHandler = ... listener?.start() When my colleague's program needs to send data, it connects to the socket created by the macOS app, and the data is received perfectly—unless the macOS app is sandboxed. I have added outgoing and incoming connections entitlements to the macOS app. I tested my colleague's program both embedded in the macOS app and separately, ensuring to add the com.apple.security.inherit entitlement as well. However, it still doesn't work when the macOS app is sandboxed. The socket file's permission is srwxr-xr-x@ and is located in the containers folder when sandboxed, and srwxr-xr-x and HOME/Library/Application Support/MyApp when not sandboxed. What could be going wrong? Does the Network Framework support this use case, or do I need to revert to using AF_UNIX? Thank you for your assistance. Best regards. ps. My colleagues' program was written in go, using a standard function conn, err := net.Dial("unix", "socket_path_in_container"). It outputs invalid argument error when the macOS App is sandboxed.
2
0
249
Jun ’24
Internet is blocked when `includeAllNetworks` is enabled and `NEHotspotHelper` is registered
Hello, We are facing what we believe is a compatibility issue with two networking APIs. If the Network extension VPN configuration has includeAllNetworks flag enabled and the NEHotspotHelper is registered. The user has internet connection but it is blocked, and there user will get internet back only after restarting the device. VPN Configuration is as below while connecting to VPN, { localizedDescription = WLVPN WireGuard Configuration enabled = YES protocolConfiguration = { serverAddress = <18-char-str> passwordReference = {length = 20, bytes = 0x67656e70ed0d05c06b1b4896bf4fef2031e1a92d} disconnectOnSleep = NO includeAllNetworks = YES excludeLocalNetworks = YES excludeCellularServices = YES excludeAPNs = YES excludeDeviceCommunication = YES enforceRoutes = NO providerBundleIdentifier = com.wlvpn.ios.consumervpn.network-extension } onDemandEnabled = NO onDemandRules = () } After running the code shown below. Regardless if the VPN is connected or not, the user needs to restart his device to regain internet access. private let neHelperQueue = DispatchQueue(label: "com.wlvpn.ios.consumervpn.hotspot", attributes: DispatchQueue.Attributes.concurrent) let options: [String: NSObject] = [kNEHotspotHelperOptionDisplayName : "" as NSObject] let status = NEHotspotHelper.register(options: nil, queue: neHelperQueue) { cmd in NSLog("Received command: \(cmd.commandType.rawValue)") } We need to use the includeAllNetworks flag to prevent the novel "Tunnel vision" vulnerability. Can we please have some help getting confirmation if both functionalities are compatible or if there's a way to enable them at the same time?
2
1
255
Jun ’24
URLSession download task fails with NSPOSIXErrorDomain error Code=1
I have a Push Notification Service Extension, which is processing notification payload to attach image, if imageUrl is key is present. I use this simple code to perform the download: let downloadTask = URLSession.shared.downloadTask(with: urlRequest) { [weak self] tempURL, response, error in /// parse results... } Notification payload contains "mutable-content" : 1 inside aps. It's entirely randomly will it work or not. When it doesn't work, I get this error: Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted" UserInfo={NSErrorFailingURLStringKey=https://w7.pngwing.com/pngs/1005/607/png-transparent-african-elephant-animal-elephant-thumbnail.png, NSErrorFailingURLKey=https://w7.pngwing.com/pngs/1005/607/png-transparent-african-elephant-animal-elephant-thumbnail.png, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDownloadTask <4A847242-2314-4125-99E4-A424CF4B4B7C>.<7>" ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <4A847242-2314-4125-99E4-A424CF4B4B7C>.<7>} I have no idea what Apple's internal code throws this error, what could possibly go wrong here. This is happening for a while now, I just re-tested on iOS 17.5.1 on 14 Pro. App is compiled using Xcode 15.4 and Swift 5.10, latest SDK. Not sure is it relevant but main iOS app has DataProtection capability set to Complete.
9
0
272
Jun ’24
IP restricted App Review
Greetings to everyone, An application we developed with our team could not get approval from Apple review. The application is restricted to local network only. So App Review Team couldn't login in the app and review it. And they says, "Please note that we cannot use a demo video showing your app in use to continue the review." How did you apply for an IP-restricted application? Then they says, "include a demonstration mode that shows all of the features and functionality available in your app" too. If you choose to include a demo mode, what features had you built-in demo mode?
1
0
268
Jun ’24
URLSessionWebSocketTask - sendPing's pongReceiveHandler called twice
Hello, I'm working on adding a URLSessionWebSocketTask based web socket connection to have live data in a single view. When the user navigates to it, the connection is established and live data is received. The task is being cancelled when this view disappears: task.cancel(with: .goingAway, reason: nil) After calling resume() on the task, I ping the server to see if the connection works before sending any messages. I opt to use async API instead of closure based wherever possible. Foundation provides both APIs for most URLSessionWebSocketTask's methods, but for some reason it misses async version of sendPing. Such method, however, is available in swift-corelibs-foundation project here. So I've added a similar code locally: extension URLSessionWebSocketTask { func sendPing() async throws { let _: Void = try await withCheckedThrowingContinuation { continuation in sendPing { error in if let error { continuation.resume(throwing: error) } else { continuation.resume() } } } } } The issue that I have is that if the user navigates from the view after sendPing was called, but before pong is received, pongReceiveHandler is called twice with error: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSDescription=Software caused connection abort} This results in an exception: Fatal error: SWIFT TASK CONTINUATION MISUSE: sendPing() tried to resume its continuation more than once, throwing Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSDescription=Software caused connection abort}! There are no issues when the task is cancelled after successful ping. The documentation does not state that pongReceiveHandler is always called only once, but by looking at the code in swift-corelibs-foundation I think that it should be the case. Am I misusing sendPing, or is it a bug in the Foundation? Perhaps there is no func sendPing() async throws for some reason? I use Xcode 15.3 with Swift 5.10. Great thanks for any help. Best Regards, Michal Pastwa
3
1
264
Jun ’24
secured HTTP connection libraries, App Uses Non-Exempt Encryption?
Hi, My application ships a copy of following cryptographic libraries: libp11-kit.0.dylib libnettle.8.dylib libgnutls.30.dylib It's purpose is to connect by secured HTTP to an optional server, that might be turned on to allow to receive HTTP requests. I think this is standard encryption, but do I need to mention this explicitely with App Uses Non-Exempt Encryption? The application doesn't encrypt content it is just for secured HTTP connections. regards, Joël
0
0
201
Jun ’24
NWConnectionGroup w/QUIC Best Practices
Hello. Wanted to ask about the right way, or the intended way to leverage NWConnectionGroup for a QUIC based streaming solution. The use case is, we are making a request from the client in order to play a movie, and we want to send as much video frames as possible (and as fast as possible) from the streaming server, which also uses the Network framework. Our understanding is, NWConnectionGroup will open a QUIC tunnel between both parties so we can multiplex different streams to the client and we are already doing that. We see a throughput of approx. 20-35MB/s (client device is an iPad and server is an M2 macbook pro running a server app) and we would like to understand if we can improve these results way more. For example: 1.- Is it a good practice to create a second tunnel (NWConnectionGroup), or is not needed here?. We tried that, but the second one is also coming with id 0 on the metadata object, just as the first group we instantiated, not sure why this is the case. 2.- We are using a pool of several NWConnection (initialized with the group object) already instantiated, that way we send a video buffer in chunks as a stream on each connection. We use one connection for a buffer and when we need to send another buffer we use a different NWConnection pulled from the pool. We maybe just want a confirmation/validation of what we are doing, or to see if we are missing something on our implementation... Thanks in advance.
2
0
239
Jun ’24
NEVPNProtocolIPsec No VPN Shared Secret was provided
Hello I am developing a react native VPN app. Also I'm new to Native Modules and Swift. Depending on the related documents, I've tried to create IPSEC VPN and connect automatically from my application. I've used the code below to create and connect IPSEC VPN but it is returning "No VPN Shared Secret was provided" error. If I try to add VPN configuration from my Iphone with same parameters it's connecting successfully.
2
0
141
Jun ’24