Networking

RSS for tag

Explore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.

Networking Documentation

Post

Replies

Boosts

Views

Activity

Significant Decrease in Network Speed After Replacing NSURLConnection with NSURLSession
Hello, I recently replaced NSURLConnection with NSURLSession in my application, and I have noticed a significant decrease in network speed. I am seeking advice on why this might be happening and how to resolve the issue. Here is the code before the change: Old Code: - (void)execute:(id<STHttpEntity>)entity { [entity addHeader:API_HDR_CLASS_NAME value:self.apiClass]; [entity addHeader:API_HDR_METHOD_NAME value:self.apiMethod]; NSMutableURLRequest *req = [self createRequest:entity]; self.connection = [[NSURLConnection alloc] initWithRequest:req delegate:self]; [self.connection start]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [self clearConnectionTimeout]; self.requestData = nil; if (self.httpStatus != HTTPSTATUS_OK) { [self callFailedWithStatus:self.httpStatus]; return; } [self callSucceeded]; } And here is the code after the change: New Code: - (void)execute:(id<STHttpEntity>)entity { [entity addHeader:API_HDR_CLASS_NAME value:self.apiClass]; [entity addHeader:API_HDR_METHOD_NAME value:self.apiMethod]; NSMutableURLRequest *req = [self createRequest:entity]; NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; self.dataTask = [session dataTaskWithRequest:req]; [self.dataTask resume]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error { [self clearConnectionTimeout]; self.requestData = nil; if (error) { [self callFailed:error]; } else { [self callSucceeded]; } } Issue: After replacing NSURLConnection with NSURLSession, the network speed has significantly decreased. The new implementation seems to be much slower than the old one. Questions: 1.What could be the reasons for the significant decrease in network speed after switching to NSURLSession? 2.Are there any specific configurations or best practices for NSURLSession that I should be aware of to improve performance? 3.Is there any known issue with NSURLSession that could cause such a performance drop? Any insights or suggestions would be greatly appreciated. Thank you in advance for your help!
1
0
149
3w
Send UDP Protocol is not working in Xcode 16 iOS18
func setupUDPSocket() { stopSearch() udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main) do { try udpSocket?.bind(toPort: 4012) try udpSocket?.beginReceiving() try udpSocket?.joinMulticastGroup("239.255.255.250") } catch let error { DispatchQueue.main.async { print(Thread.current) print(error) print(error) } } } private func search() { guard let udpSocket = udpSocket else { print("not set udpSocket") stopSearch() return } let message = "M-SEARCH * HTTP/1.1\r\n" + "HOST: 239.255.255.250:1900\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: 3\r\n" + "ST: ssdp:all\r\n" + "\r\n" let data = message.data(using: .utf8)! udpSocket.send(data, toHost: "239.255.255.250", port: 1900, withTimeout: -1, tag: 0) } This is my send SSDP code, my project was inited in Objective-C, recently I update xcode to 16, I get Error Domain=NSPOSIXErrorDomain Code=65 "No route to host", when I send UPD data in iOS 18, but iOS 17 is ok. Even I found, if I init a new project in Swift, this bug is disappear.
1
0
185
3w
Local Network Privacy FAQ
IMPORTANT This FAQ has been replaced by TN3179 Understanding local network privacy. I’m leaving this post in place as a historical curiosity, but please consult the technote going forward. 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, visionOS, and macOS. It’s not implemented on other platforms, most notably tvOS. IMPORTANT macOS 15 (currently in beta) introduced local network privacy support to the Mac. WWDC 2024 Session 10123 What’s new in privacy is the official announcement. This works much like it does on iOS, but there are some subtle differences. I’ll update this FAQ as I gain more experience with this change. 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 2024-10-31 Added a link to this FAQ’s replacement, TN3179 Understanding local network privacy. 2024-07-22 Added a callout explaining that local network privacy is now an issue on macOS. 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.
0
0
18k
Oct ’20
Prioritizing QUIC streams?
When creating multiple QUIC streams (NWConnections) sharing one QUIC tunnel (using NWMultiplexGroup), is it possible to assign different priorities to the streams? And if yes, how? The only prioritization option I found so far is NWConnection.ContentContext.relativePriority, but I assume that is for prioritizing messages within a single NWConnection?
5
0
228
Oct ’24
Local Network Privacy pop-up on macos Sequoia for CLI Tools Invoked by Launchd Daemon
Starting from macOS 15 (macOS Sequoia), a new pop-up is triggered: “Local Network Privacy.” We have some questions regarding this new pop-up on MacOS: Question 1: If a launchd daemon invokes a command-line tool, will this tool trigger the local network prompt if it attempts to access the network? We use a launchd daemon which runs in root context and is started from /Library/LanuchDaemons/ Question 2: How will this prompt work across various macOS executables? I have read other developer forum articles and the https://developer.apple.com/forums/thread/663858 - Local Network Privacy FAQ. The responses are a little unclear and any insight into these questions would be very helpful with this new requirements.
1
0
151
3w
applicationWillResignActive method not triggering API call as expected
I'm currently working on an iOS app where I need to trigger an API call as soon as applicationWillResignActive is called. The method is designed to save user data and sync certain settings before the app transitions to the background. However, I'm experiencing issues where the API call is not consistently being triggered within this method. Does applicationWillResignActive not fully warrant an api call?
1
0
107
3w
Query Regarding NEFilterDataProvider's Hostname Resolution Across Different Browsers
PLATFORM AND VERSION macOS Development environment: Xcode 15.0, macOS 15.0.1 Run-time configuration: macOS 15.0.1 DESCRIPTION OF PROBLEM We are currently developing a macOS app using the NEFilterDataProvider in the Network Extension framework, and we've encountered an issue regarding hostname resolution that we would like your guidance on. In our implementation, we need to drop network flows based on the hostname. The app successfully receives the remoteHostname or remoteEndpoint.hostname for browsers such as Safari and Mozilla Firefox. However, for other browsers like Chrome, Opera Mini, Arc, Brave, and Edge, we only receive the IP address instead of the hostname. We are particularly looking for a way to retrieve the hostname for all browsers to apply our filtering logic consistently. Could you please advise whether there is any additional configuration or API we can use to ensure that we receive hostnames for these browsers as well? Alternatively, is this a limitation of the browsers themselves, and should we expect to only receive IP addresses for certain cases? STEPS TO REPRODUCE For Chrome, Brave, Edge, and Arc browsers you won't receive the hostname in NEFilterFlow. Using the same sample project provided in WWDC 2019 https://developer.apple.com/documentation/networkextension/filtering_network_traffic import NetworkExtension import os.log import Network /** The FilterDataProvider class handles connections that match the installed rules by prompting the user to allow or deny the connections. */ class FilterDataProvider: NEFilterDataProvider { // MARK: NEFilterDataProvider override func startFilter(completionHandler: @escaping (Error?) -> Void) { completionHandler(nil) } override func stopFilter(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { completionHandler() } override func handleNewFlow(_ flow: NEFilterFlow) -> NEFilterNewFlowVerdict { guard let socketFlow = flow as? NEFilterSocketFlow, let remoteEndpoint = socketFlow.remoteEndpoint as? NWHostEndpoint, let localEndpoint = socketFlow.localEndpoint as? NWHostEndpoint else { return .allow() } var hostName: String? = nil // Attempt to use the URL host for native apps (e.g., Safari) if let url = socketFlow.url { hostName = url.host os_log("URL-based Host: %@", hostName ?? "No host found") } // Fallback: Use remote hostname for third-party browsers like Chrome if hostName == nil { if #available(macOS 11.0, *), let remoteHostname = socketFlow.remoteHostname { hostName = remoteHostname os_log("Remote Hostname: %@", hostName ?? "No hostname found") } else { hostName = remoteEndpoint.hostname os_log("IP-based Hostname: %@", hostName ?? "No hostname found") } } let flowInfo = [ FlowInfoKey.localPort.rawValue: localEndpoint.port, FlowInfoKey.remoteAddress.rawValue: remoteEndpoint.hostname, FlowInfoKey.hostName.rawValue: hostName ?? "No host found" ] // Ask the app to prompt the user let prompted = IPCConnection.shared.promptUser(aboutFlow: flowInfo, rawFlow: flow) { allow in let userVerdict: NEFilterNewFlowVerdict = allow ? .allow() : .drop() self.resumeFlow(flow, with: userVerdict) } guard prompted else { return .allow() } return .pause() } // Helper function to check if a string is an IP address func isIPAddress(_ hostName: String) -> Bool { var sin = sockaddr_in() var sin6 = sockaddr_in6() if hostName.withCString({ inet_pton(AF_INET, $0, &sin.sin_addr) }) == 1 { return true } else if hostName.withCString({ inet_pton(AF_INET6, $0, &sin6.sin6_addr) }) == 1 { return true } return false } }
1
3
153
3w
Issue with Network Flow Detection using NEFilterDataProvider in iOS Network Extension.
PLATFORM AND VERSION iOS Development environment: Xcode 16.0, macOS 15.0.1 Run-time configuration: iOS 17.5.1 DESCRIPTION OF PROBLEM We are working on an iOS application that utilizes the NEFilterDataProvider class from the Network Extension framework to control network flows. However, we are encountering an issue where network flows are not being detected as expected. Here are the details of our setup: We are using the NEFilterDataProvider class to filter network traffic in our app. The filtering setup works well for certain flows/apps, but we cannot detect Facebook network flows as intended. The app is correctly configured with the necessary entitlements, and we have set up the required App Groups and Network Extension capabilities. We would like to request guidance on how to troubleshoot or resolve this issue. Could you provide insights on: Whether there are any known limitations or conditions under which network flows may not be detected by NEFilterDataProvider. Recommendations for additional debugging techniques to better understand why some flows might not be captured. Recommendations for additional code to be added to detect some flows that might not be captured. Any specific scenarios or configurations that might be causing this issue in iOS. STEPS TO CHECK Replace below code in FilterDataProvider. Try running the app and set debugger in FilterDataProvider. Launch Facebook app. You will observe that no NEFilterFlow is detected in handleNewFlow for actions such as posts, reels, etc. import NetworkExtension class FilterDataProvider: NEFilterDataProvider { let blockedDomains = [ "facebook.com" ] override func startFilter(completionHandler: @escaping (Error?) -> Void) { // Perform any necessary setup here. DNSLogger.shared.log(message: "Filter started") completionHandler(nil) } override func stopFilter(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { // Perform any necessary cleanup here. DNSLogger.shared.log(message: "Filter stopped with reason: \(reason)") completionHandler() } override func handleNewFlow(_ flow: NEFilterFlow) -> NEFilterNewFlowVerdict { var url: URL? if let urlFlow = flow as? NEFilterBrowserFlow { url = urlFlow.url } else { let urlFlow = flow as? NEFilterSocketFlow url = urlFlow?.url } guard let hostName = url?.host else { return .allow() } DNSLogger.shared.log(message: "Domain reveived: \(hostName)") return .allow() } // Handle inbound data (data received from the network) override func handleInboundData(from flow: NEFilterFlow, readBytesStartOffset offset: Int, readBytes: Data) -> NEFilterDataVerdict { DNSLogger.shared.log(message: "Inbound data: \(readBytes)") return .needRules() } // Handle outbound data (data sent to the network) override func handleOutboundData(from flow: NEFilterFlow, readBytesStartOffset offset: Int, readBytes: Data) -> NEFilterDataVerdict { // Inspect or modify outbound data if needed // For example, you could log the data or modify it before sending DNSLogger.shared.log(message: "Outbound data: \(readBytes)") return .needRules() } override func handleRemediation(for flow: NEFilterFlow) -> NEFilterRemediationVerdict { return .needRules() } override func handleRulesChanged() { // Handle any changes to the rules } }
1
4
167
3w
I want to establish connection between iOS app and Apple TV via WIFI to develop apple tv remote app, Any one have idea how?
I'm looking to develop an iOS application that functions as a remote for Apple TV, including discovering Apple TV devices over Wi-Fi. If anyone has experience building similar applications, could you share insights on available frameworks or protocols to discover Apple TVs? Additionally, if there are reference apps on the App Store that work like Apple's default remote app, I would greatly appreciate recommendations. Any guidance from developers who have worked on similar projects would be very helpful!
1
0
161
3w
VPN issue in iOS 18.1 RC
After installing iOS 18.1 RC, VPN using IKEv2 and Wireguard protocols stopped working. VPN successfully connects, but there is no internet. On older versions everything works fine. On OpenVPN protocol everything works fine. I haven't found any errors in Console.log.
2
0
449
3w
RCS failing on iOS 18 when VPN active
When a VPN is active, RCS messaging does not work on iOS 18. I work on an iOS VPN app, and we were very appreciative of the excludeCellularServices network flag that was released during the iOS 16 cycle. It's a great solution to ensure the VPN doesn't interfere with cellular network features from the cellular provider. Separately - As a user, I'm excited that iOS 18 includes RCS messaging. Unfortunately, RCS messaging is not working when our VPN is active (when checking on the iOS 18 release candidate). My guess is that RCS is not excluded from the VPN tunnel, even when excludeCellularServices is true. It seems like RCS should be added in this situation, as it is a cell provider service. Can RCS be added as a service that is excluded from the VPN tunnel when excludeCellularServices is true? (I've also sent this via feedback assistant, as 15094270.)
3
1
781
Sep ’24
UpdateApplicationContext not working simulator
I am having problems on Xcode13.3.1, Monterey 12.2.1, Apple M1 Max. Sending an UpdateApplicationContext update from a paired iPhone simulator is not received on the paired Apple Watch Simulator in the didRecieveApplicationContext. However, sendMessage from the apple watch simulator does update the iphone simulator app properly. It is however, not possible to send anything from the paired iPhone simulator to the paired Apple Watch Simulator. When working with actual devices everything works properly with WatchConnectivity with passing information back and forth via updateapplicationcontext and sendmessage calls. Can anyone confirm this is a bug or if there is something wrong with my setup?
2
0
1.5k
Apr ’22
Authority application results not returned
I applied to Apple for authorization for the following page about 3 weeks ago, but have not received the results yet https://developer.apple.com/documentation/networkextension/local_push_connectivity Should I try to submit the application again with the same information or can I wait a little longer? I would appreciate it if you could give me a little information about the same application or even another authority, such as the time it took to reply to that application.  Here is the actual page I applied for https://developer.apple.com/contact/request/local-push-connectivity
2
0
144
4w
Matter controller permissions after device commissioning
I have tried filing a feedback, FB15509991, for help with this and that didn't go anywhere. Figured I would try the developer forums. Overview I am working on a matter device using the Matter SDK and the matter device basically consists of both a matter bridge and matter controller functionality. The bridge part is currently a none-issue, however trying to have our device be an additional controller for the existing matter fabric. The overall idea for our device as a matter controller is that it can be commissioned with Apple Home (via Matter BLE commissioning) and then view and control existing matter devices (over Wi-Fi network) on the Homekit matter fabric (convenient user experience), instead of our device having to form a matter fabric of its own and then having the user re-commission all their devices to add them our controller (difficult and possibly frustrating user experience), in order to have a consistent control experience between our device's display and Apple Home app. The big problem When we onboard our device via Apple Home app it does not have attribute write permission to other devices on the same fabric as we are seeing Unsupported Access (IM:0x0000057E) responses instead of expected attribute changes. Same for attempts to read valid endpoint/cluster/attributes. The possible solution Our operational device needs to be added to the access control list (ACL) with View and Operator permissions and then the ACL update pushed to all the fabric devices in order to give our device controller access to them. The next problem My question is what do we have to do in order for our device will be given control access permissions (View + Operator) in an ACL (access control list) update to other devices after our device has been commissioned? Because the matter specification does not define a "Controller Cluster" that could be used to type a device as a matter controller to make it obvious that the device wishes to have controller permissions post commissioning. So that means its up to each fabric administrator implementer as to how to accomplish what I'm requesting to do. I'm hoping somebody in the Apple team responsible for the Matter + HomeKit integration could give me some insight as to whether this is even possible at this time. Test environment The environment consists of: iPhone running iOS 17.7 iPad running iPadOS 18.0.1 HomePod Mini with software version 18.0 Realtek WiFi module running Matter Fan+Light firmware (Matter SDK 1.3) for target/controlee [our device] LCD display unit + Realtek WiFi module (Matter SDK 1.3) for controller.
1
0
171
4w
A server with the specified hostname could not be found exception
Hi, I have been working on the app that implements DNS Proxy Extension for a while now, and after a couple builds to TestFlight I noticed that I got a couple crashes that seem to be triggered by EXC_BREAKPOINT (SIGTRAP) After some investigation, it was found that crashes are connected to CFNetwork framework. So, I decided to additionally look into memory issues, but I found the app has no obvious memory leaks, no memory regression (within recommended 25%, actual value is at 20% as of right now), but the app still uses 11mb of memory footprint and most of it (6.5 mb is Swift metadata). At this point, not sure what's triggering those crashes, but I noticed that sometimes app will return message like this to the console (this example is for PostHog api that I use in the app): Task <0ABDCF4A-9653-4583-9150-EC11D852CA9E>.<1> finished with error [18 446 744 073 709 550 613] Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={_kCFStreamErrorCodeKey=8, NSUnderlyingError=0x1072df0f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, _NSURLErrorNWResolutionReportKey=Resolved 0 endpoints in 2ms using unknown from cache, _NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: en0[802.11], ipv4, dns, uses wifi}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <0ABDCF4A-9653-4583-9150-EC11D852CA9E>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalUploadTask <0ABDCF4A-9653-4583-9150-EC11D852CA9E>.<1>" ), NSLocalizedDescription=A server with the specified hostname could not be found., NSErrorFailingURLStringKey=https://us.i.posthog.com/batch, NSErrorFailingURLKey=https://us.i.posthog.com/batch, _kCFStreamErrorDomainKey=12} If DNS Proxy Provider uses custom DoH server for resolving packets, could the cache policy for URLSession be a reason? I had a couple other ideas (HTTP3 failure, CFNetwork core issues like described here) but not sure if they are valid Would be grateful if someone could give me a hint of what I should look at
18
0
776
Sep ’24
Network Framework 'connection.receive' <error> = 89
I have the following snippet of code for receiving incoming data on a NWConnection: self.Connection.receive(minimumIncompleteLength: 1, maximumLength: self.MAX_INTAKE) { (data, context, isComplete, error) in if let err = error { // receive <error> returned non-nil self.Connection.cancel() return // exit completion handler } ... } This generally works and rarely receives an error. But seemingly at random, will return 89. When this happens I've been sending a .cancel before returning from the completion handler. It will work great for tens of thousands of connections, then suddenly return 89 error codes. My question is: Should I be canceling the connection here or simply let NWFramwwork do as it will? Canceling the connection seems to throw my NGINX reverse proxy into fits, from which it never recovers without a restart. In short what is the best practice for handling errors when receiving bytes in NWFramework?
2
0
211
3w
Custom Property when creating a NWConnection
I am developing an App using the Networking framework, which can be either a Socket Server or a Socket Client, such that 2 devices can communicate remotely. I would like to include the Client's userUID when creating a NWConnection, such that when the SocketServer accepts the connection, it knows immediately which user is connected. (Currently I achieve this by sending the UserUID in Welcome/Introduction messages, which seems an unnecessary overhead, and because I am using UDP, I also have to make sure these messages are acknowledged, before safely using the connection.) Is there a way to add this custom data into the NWConnection?
2
0
174
3w
Launching Network System Extension from automated installation
We have network system extension which is fundamental part of our application and needs to be installed before the application can run. In many cases we need the installation to be automated, i.e. without logged-in user (with the help of MDM solution like JAMF). Is there a way to activate the extension fully automated without logged-in users? I tried to call 'open -W -a /Application/' from the package's post install script. But seems launch fails if no user is logged in.
1
0
151
3w
5G Network Slicing and NetworkExtension
Hello, I am writing a NetworkExtension VPN using custom protocol and our client would like to able to use 5G network slice on the VPN, is this possible at all? From Apple's documentation, I found the following statement: If both network slicing and VPN are configured for an app or device, the VPN connection takes precedence over the network slice, rendering the network slice unused. Is it possible to assign a network slice on a NetworkExtension-based VPN and let the VPN traffic uses the assign network slice? Many thanks
0
0
136
4w