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

Posts under Networking subtopic

Post

Replies

Boosts

Views

Activity

STOP and remove all incoming connection,, I used chatgpt but did give right answers
➜ ~ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --listapps Then Password Total number of apps = 6 1 : /Users/rks/Library/Android/sdk/platform-tools/adb (Block incoming connections) 2 : /Applications/Google Chrome.app/Contents/MacOS/Google Chrome (Block incoming connections) 3 : /usr/libexec/sshd-keygen-wrapper (Block incoming connections) 4 : com.apple.WebKit.Networking (Allow incoming connections) 5 : com.netacad.PacketTracer8.0.1 (Allow incoming connections) 6 : com.wangxutech.MacLetsView (Allow incoming connections) ➜ ~
1
0
345
Oct ’24
Network Service Order for IoT Ethernet device
I am making a USB attached IoT device that follows the Matter approach to connectivity (IP/mDNS/DHCP). I am having conflicts with it as it appears to MacOS as an Ethernet adapter and this is causing it to be assigned as a "default" route, interfering with routing when my Mac is connected to NAT based WiFi. I'd like to be able to hint to MacOS & iPadOS that this is not a routable private network, the subnet should be respected and a default route should not be assigned to it, otherwise the order of the device connection is used by the IP routing tables and I am concerned my non-routable private network will initialize before Wifi and block NAT based internet connectivity. How can I hint to MacOS/iPadOS "this is not a routable private network, this is not a NAT, do not assign me a default route beyond the subnet I have provided you."
1
0
83
Apr ’25
Getting list of wifi networks nearby with a specific prefix
I'm building an app that helps manage my own wifi access points. Now, all my wifis emit SSIDs starting with the same prefix. Is it possible for me to list down all the SSIDs near me that start with that prefix, so that determine which of my wifis are near me? (Swift) Can NEHotspotHelper or NEHotspotConfigurationManager help in this regard?
1
1
283
Feb ’25
Issue with WebSocket Secure (wss) connection on iOS (works on Node.js, fails on iOS app)
Hello everyone, I’m developing an iOS application that uses WebSocket Secure (wss) to connect to a backend server, which is working correctly. The server is hosted on Render.com and accepts connections over https and wss. Context: • I can connect to the backend without issues using HTTPS from both the app and a web browser. • Using Node.js and the Socket.IO client, the WebSocket connection to the server works correctly over wss://. • The server is configured with a valid SSL certificate (the HTTPS connection is verified and works in a browser). • The problem occurs when I try to connect from the iOS client (using Socket.IO in Swift) to the server through wss://social-gamer-backend.onrender.com. The connection consistently fails on iOS. The Issue: Even though the URL is correctly configured, and I can connect via Node.js, when I attempt to connect from the iOS app, I get connection-related errors. The most common error is: Error while connecting to the socket: Tried emitting when not connected • The server URL is correct (wss://social-gamer-backend.onrender.com). • The JWT token is being sent correctly in the headers. • There are no visible SSL certificate issues since the HTTPS connection works fine. • I’ve tried enabling and disabling App Transport Security (ATS) in the Info.plist. • From Node.js, the same connection code works fine, indicating that the WebSocket server is active and operational. Current iOS Configuration: let manager = SocketManager(socketURL: url, config: [ .log(true), .compress, .reconnects(true), .forceWebsockets(true), .extraHeaders(["Authorization": "Bearer (token)"]) ]) What I’ve tried so far: 1. I’ve tested the connection on different networks, including Wi-Fi and mobile data. 2. I’ve checked the iOS device restrictions and disabled potential network limitations. 3. I’ve enabled detailed logs in Crashlytics, but I can’t find any relevant information indicating why the connection is failing. 4. The same URL with wss:// works on Node.js, so it’s not an issue with the WebSocket server. Question: What could be preventing the iOS app from establishing a successful connection to the WebSocket server over wss://? Is there anything else I should configure in the app or server to allow iOS to handle secure WebSocket connections? I would appreciate any help or suggestions to resolve this issue. Thank you in advance.
1
0
743
Oct ’24
Wifi SSID Detection
I have a single ssid that I would like to connect users to, which I can do easily with the NetworkExtension api. The only additional feature I want to add is being able to detect the availability of the ssid before connecting to it. I have checked the forums and looked through things like the Hotspot Helper Docs. From what I can tell, this just isn't possible. So, two questions I have: Is this definitely impossible? Any recommended alternatives for simulating this type of behavior? Thanks!
1
0
220
Jan ’25
What is the exact function of UIRequiresPersistentWiFi?
According to the Apple documentation, if this value is NO, the Wi-Fi connection will be disconnected after the application is used for 30 minutes; but after actual testing, it doesn't happen. So what exactly is the specific function of UIRequiresPersistentWiFi? If the value of UIRequiresPersistentWiFi is NO, it will disconnect Wi-Fi. What conditions does the device need to meet or in which situations will it disconnect Wi-Fi?
1
0
299
Oct ’24
"Internal Error"(8) occurs in a function of the NEHotspotConfigurationManager class.
Hello all, I have a question, I am developing an application that uses the apply() function of the NEHotspotConfigurationManager class to switch the Wifi of the device. In the completionHandler of the apply() function, the error argument contains “Internal Error(8)” and the wifi switching may fail. We have never seen this problem during development, and since it occurs only in the market, we are at a loss as to the cause and countermeasure. Do you know the cause of the “Internal Error(8)” and how to fix it? A similar phenomenon has already been discussed in the following thread, but after countermeasures were taken in iOS12, it also occurs in iOS13 and later and no progress has been made since then. https://developer.apple.com/forums/thread/107851 I would appreciate it if someone could clarify what is happening with this error, as there is not much information on the web regarding this error. Thank you in advance.
1
0
236
Nov ’24
Accessory Setup Kit - Set WIFI SSID to ASAccessory after initial setup
I have an accessory which uses both Bluetooth and WiFi to communicate with the app. I am trying to migrate to Accessory Setup Kit. However, the API expects both the bluetooth identifiers and WIFI SSID or SSID prefix in the ASDiscoveryDescriptor. The problem is we only have the WIFI SSID after BLE pairing. Our current flow looks like this: Pair via BLE Connect via BLE Send a BLE command to request WIFI settings (SSID and password) (Each device has a different SSID and password) Connect to WI-FI hotspot by calling NEHotspotConfigurationManager applyConfiguration with the retrieved credentials. Is there a way to set the Wi-Fi SSID of an ASAccessory object after the initial setup? To use Accessory Setup Kit we would need something like this: Call Accessory Setup Kit with bluetooth identifiers in the descriptor, finish the setup and get ASAccessory object. Connect via BLE Send a BLE command to request WIFI settings (SSID and password) Set the SSID of the ASAccessory to the retrieved value. Connect to WI-FI hotspot by calling `NEHotspotConfigurationManager joinAccessoryHotspot. Thanks!
1
0
244
Feb ’25
iOS reports incorrect own IP address to apps when connected to WiFi
I have an iPhone app which relies heavily on TCP/IP communication in the local network. Therefore, the application starts a server socket and accepts incoming connections. This worked flawlessly for a long time and we had no problems with this. Problem In the last days however, we observed that for some iPhones with the server role other devices cannot connect to the server of our app. The server does not accept incoming connections on the devices IP address and the client times out. Environment Both iPhones (the server and the client) are in the same network with 192.168.1.0 address range and 255.255.255.0 subnet mask. The server has the IP 192.168.1.11 and the client has 192.168.1.22. This is a normal home WiFi network with no special firewall rules. Both devices have mobile data disabled and the "access local network" permission is granted. The server socket is bound to all interfaces (0.0.0.0). More technical symptoms When the server iPhone is in this faulty state, it seems like it somehow has two ip addresses: 192.168.2.123 and 192.168.1.11 The WiFi preferences show the (correct) .1.11 ip address. The Apps however see the (wrong) .2.123 ip address. I cannot explain where the other ip address comes from and why the device thinks it has this ip address. I've collected interface diagnosis information on a faulty iPhone and it listed the following interfaces and IPs: en0 -> 192.168.2.123 lo0 -> 127.0.0.1 pdp_ip0 (cellular) -> 192.0.0.2 pdp_ip1 to pdp_ip6 (cellular) -> -/- ipsec0 to ipsec6 (vpn) -> -/- llw0 (vpn) -> -/- awdl0 -> -/- anpi0 -> -/- ap1 -> -/- XHC0 -> -/- en1 and en2 (wired) -> -/- utun0 to utun2 (vpn) -> -/- The correct ip of the device is not listed anywhere in this list. A reboot helped to temporarily fix this problem. One user reported the same issue again a few hours later after a reboot. Switching off WiFi and reconnecting does not solve the problem. This issue occurred on several iPhones with the following specs: iOS Version 18.1.1, 18.3.1 iPhone 13 Pro, iPhone 13 Pro Max, iPhone 15 Pro The problem must be on the server side as the client can successfully connect to any other device in the same network. Question(s) Where does this second IP come from and why does the server not accept connections to either ip even though it is bound to 0.0.0.0? Are there any iOS system settings which could lead to this problem? (privacy setting, vpn, ...) What could be done to permanently fix this issue?
1
0
215
Mar ’25
CentralManager won't connect to device for watchOS, but will for iOS?
Hi there, I'm having an issue hoping someone could help. We have an iOS app that uses CoreBluetooth to connect to peripherals using the central manager. The app works great - However, when using the same exact central manager for our watchos app, it will attempt to connect, but I never get a callback for either didConnect or didFailToConnect. The watch can connect successfully to other BLE devices, so the watch itself is capable of BLE connectivity. Here's a list of thing's I've tried (unsuccessfully): 1) Added every bluetooth-related entitlement to info.plist Privacy - Bluetooth Always Usage Description Privacy - Bluetooth Peripheral Usage Description Background Modes: App communicates using CoreBluetooth, App shares data using CoreBluetooth 2) Checked for Single-Connection Limits Verified that the iPhone was fully disconnected from the peripheral to ensure the device wasn’t limited to one connection. Attempted to connect on watchOS alone (with iPhone turned off) 3) Tried various options for CBCentralManager, scanForPeripherals, and connect I went through all the keys for various options and tried just setting them, they had no effect CBCentralManagerOptionShowPowerAlertKey, CBConnectPeripheralOptionEnableTransportBridgingKey Item 2 4) Tried .registerForConnectionEvents() 5) Set peripheral's delegate to the central in the didDiscover, stored it in a variable to ensure a strong reference to it I get no warnings either. The last time I ran into something like this, I found out the watchOS blocks TCP sockets. If I print out the CBPeripheralState a few seconds after trying to connect, it shows its stuck on CBPeripheralStateConnecting. Any advice or direction is greatly appreciated Below is the code and various print outs (day 2 into debugging, so it's not pretty) class WatchBLEManager:NSObject,CBCentralManagerDelegate, ObservableObject{ var centralManager: CBCentralManager? @Published var devices : [String:AtomBLEDevice] = [:] private var scanningDevice:AtomBLEDevice? var bleStatus:WatchBLEStatus = .blePoweredOff func startBLE() { centralManager = CBCentralManager(delegate: self, queue: nil,options: [CBCentralManagerOptionShowPowerAlertKey: true]) self.centralManager?.delegate = self } func startScan() { self.centralManager?.scanForPeripherals(withServices: [],options: [CBCentralManagerScanOptionAllowDuplicatesKey : true]) self.centralManager?.delegate = self } func stopScan() { print("stopping scan") self.centralManager?.stopScan() filterName = "" scanningDevice = nil } func centralManagerDidUpdateState(_ central: CBCentralManager) { switch (central.state) { //... other states omitted case .poweredOff: bleStatus = .blePoweredOff // bleStateDelegate?.didBlePoweredOff() for device in devices.values{ device.isConnected = false } print("BLE is Powered Off") case .poweredOn: bleStatus = .blePoweredOn // bleStateDelegate?.didBlePoweredOn() startScan() centralManager?.registerForConnectionEvents() print("Central supports extended scan and connect: ", CBCentralManager.supports(.extendedScanAndConnect)) print("powered on") @unknown default: print("BLE is Unknown") } } private let connectionQueue = DispatchQueue(label: "com.atom.connectionQueue") var connectingTo: String? = nil var peripheral: CBPeripheral? = nil func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { guard let localName = advertisementData[CBAdvertisementDataLocalNameKey] as? String else { return} if localName.contains("Atom") { print("\nConnecting to \(localName)") print("\tAdvertising data: \(advertisementData)") print("\tANCS Authorized: ",peripheral.ancsAuthorized) print("\tServices", peripheral.services, "\n") self.peripheral = peripheral self.peripheral?.delegate = self // central.registerForConnectionEvents() // central.delegate = self peripheral.delegate = self DispatchQueue.main.async { // central.connect(peripheral) self.centralManager?.connect(peripheral, options: [ CBConnectPeripheralOptionEnableTransportBridgingKey: true]) } DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { print("\tState", String(describing: peripheral.state)) print("Connected Peripherals: \(self.centralManager?.retrieveConnectedPeripherals(withServices: []))") } } } // Never gets called for watchos func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { print("Connected to peripheral: \(peripheral.identifier)") if let atomDevice = getAtomBLEDevice(peripheral: peripheral) { //atomDevice.setPeripheral(perpipheral: <#T##CBPeripheral?#>) atomDevice.isConnected = true atomDevice.isConnecting = false //delegate?.didConnected(atomBLE: atomDevice!) atomDevice.startDiscoveringService() //atomDevice?.delegate?.didConnected(atomBLE: atomDevice!) print("Connected: \(peripheral.name)") } else { print("no matching atom device found for didConnect") print("connected peripheral :",peripheral.identifier.uuidString) } } func centralManager(_ central: CBCentralManager, connectionEventDidOccur event: CBConnectionEvent, for peripheral: CBPeripheral) { print("Connection event: \(event)") } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: (any Error)?) { print("Failed to connect: \(error?.localizedDescription)") } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { let atomDevice = getAtomBLEDevice(peripheral: peripheral) atomDevice?.isConnected = false print("Peripheral disconnected:\(peripheral.name)") } func clearData() { filterName = "" for device in devices.values{ disconnect(atomBLEDevice: device) device.perpipheral?.delegate = nil } devices = [:] scanningDevice = nil // delegate = nil centralManager = nil } } extension WatchBLEManager: CBPeripheralDelegate { }```
1
0
283
Feb ’25
CocoaMQTT(error): The deliver delegate is nil!!! the frame will be drop
I am trying to connect to MQTT broker, in very simple steps, but I am getting error CocoaMQTT(error): The deliver delegate is nil!!! the frame will be drop:PUBLISH(id: 2, topic: your-topic, payload: [72, 101, 108,...] I have create one class as: import CocoaMQTT class MQTTManager: CocoaMQTTDelegate { var mqtt: CocoaMQTT! func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) { print("Published message with ID: \(id)") } func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopics success: NSDictionary, failed: [String]) { print("Subscribed to topics: \(success)") } func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopics topics: [String]) { print("Unsubscribed from topics: \(topics)") } func mqttDidPing(_ mqtt: CocoaMQTT) { print("Pinged!") } func mqttDidReceivePong(_ mqtt: CocoaMQTT) { print("Ponged!") } func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: (any Error)?) { print("Disconnected from the MQTT") } func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) { if ack == .accept { print("Connected to the MQTT!") } else { print("Failed to connect to MQTT") } } func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) { print("Data published successfully") } func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) { if let messageString = message.string { print("Received message on topic \(message.topic): \(messageString)") } } func connectMQTT() { mqtt = CocoaMQTT.init(clientID: "your-client-id-435345", host: "your-client-id-435345", port: 1883) //tried with CocoaMQTT(clientID: "your-client-id-435345", host: "your-client-id-435345", port: 1883) mqtt.delegate = self mqtt.connect() } func subscribeToTopic(topic: String) { mqtt.subscribe(topic) } func publishData(topic: String, message: String) { mqtt.publish(topic, withString: message, qos: .qos1) } } I am trying to use it in function as: func sendTelemetryMsg(password: String, url: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void { let mqttManager = MQTTManager(); mqttManager.connectMQTT() // Subscribe to a topic let topic = "your-topic" mqttManager.subscribeToTopic(topic: topic) // Publish data to the IoT device let message = "Hello, IoT Device!" mqttManager.publishData(topic: topic, message: message) }
1
0
409
Oct ’24
Error Domain=com.apple.wifi.apple80211API.error Code=-528342014 "tmpErr"
On my macOS 15.x device, frequently encountering the error: Error Domain=com.apple.wifi.apple80211API.error Code=-528342014 "tmpErr" when connecting to an EAP WiFi network using CWWiFiClient. Restarting the device temporarily resolves the issue, but it reoccurs after some time. What could be causing this, and how can it be resolved programmatically?
1
0
365
Mar ’25
NWConnection Websocket send error
I'm attempting to use NWConnection as a websocket given a NWEndpoint returned by NWBrowser, setup like: let tcpOptions = NWProtocolTCP.Options() tcpOptions.enableKeepalive = true tcpOptions.keepaliveIdle = 2 let parameters = NWParameters(tls: nil, tcp: tcpOptions) parameters.allowLocalEndpointReuse = true parameters.includePeerToPeer = true let options = NWProtocolWebSocket.Options() options.autoReplyPing = true options.skipHandshake = true parameters.defaultProtocolStack.applicationProtocols.insert(options, at: 0) self.connection = NWConnection(to: endpoint, using: parameters) The initial connection does make it to the ready state but when I first try to send a text message over the websocket, i get nw_read_request_report [C1] Receive failed with error "Input/output error" nw_flow_prepare_output_frames Failing the write requests [5: Input/output error] nw_write_request_report [C1] Send failed with error "Input/output error" immediately, and the websocket is closed. Send code here: let encoder = JSONEncoder() let dataMessage = try encoder.encode(myMessage) let messageMetadata = NWProtocolWebSocket.Metadata(opcode: .text) let context = NWConnection.ContentContext(identifier: "send", metadata: [messageMetadata]) connection.send(content: dataMessage, contentContext: context, completion: .contentProcessed({ error in if let error = error { print (error) } })) What would typically cause the Input/output error when writing? Am I doing something obviously wrong or is there something else I can do to get additional debug information? Thanks in advance for any help.
1
0
407
Dec ’24
NEAppPushProvider Stop not being called after disconnecting from specified SSID
Hello, I have been implementing NEAppPushProvider class to establish my own protocol to directly communicate with our provider server without the need to rely on APNs for background push notifications. I am at a stage where I am able to establish a tcp communicator and receive messages back and forth but I noticed that when I disconnect from the WIFI I've set up by setting a given SSID, I am not getting hit on the Stop method. Below is briefly how I load and save preferences. NEAppPushManager appPushManager = new NEAppPushManager(); appPushManager.LoadFromPreferences((error) =&gt; { if (error != null) { Console.WriteLine($"Error loading NEAppPushManager preferences: {error.LocalizedDescription}"); return; } if (!enable) { Console.WriteLine("Disabling Local Push Provider..."); appPushManager.Enabled = false; // ✅ Immediately update UserDefaults before saving preferences userDefaults.SetBool(false, Constants.IsLocalPushEnabled); userDefaults.Synchronize(); appPushManager.SaveToPreferences((saveError) =&gt; { if (saveError != null) { Console.WriteLine($"Error disabling Local Push: {saveError.LocalizedDescription}"); } else { Console.WriteLine("Local Push successfully disabled."); } }); return; } // ✅ Now we can safely enable Local Push Console.WriteLine($"Enabling Local Push for SSID: {_currentSSID}"); appPushManager.MatchSsids = new string[] { _currentSSID }; appPushManager.LocalizedDescription = "LocalPushProvider"; appPushManager.ProviderBundleIdentifier = Constants.LocalPushExtensionBundleId; appPushManager.Enabled = true; appPushManager.SaveToPreferences((saveError) =&gt; { if (saveError != null) { Console.WriteLine($"Error saving Local Push settings: {saveError.LocalizedDescription}"); } else { Console.WriteLine("✅ Local Push successfully registered."); userDefaults.SetBool(true, Constants.IsLocalPushEnabled); userDefaults.Synchronize(); } }); }); I've read through documentation and was expecting the Stop method to be hit when I turn off Wifi. Am I missing anything? Please let me know if I should provide more info. Currently I just have a console writeline method inside the Stop method to see if it actually gets hit.
1
0
274
Feb ’25
Some confusion about VPN global routing
I am currently developing a custom-protocol VPN application for iOS using PacketTunnelProvider. I have also integrated an HTTP proxy service, which is launched via a dylib. The overall flow is as follows: App -> VPN TUN -> Local HTTP Proxy -> External Network I have a question: I am capturing all traffic, and normally, requests sent out by the HTTP proxy are also captured again by the VPN. However, when I send requests using createUdpSession in my code, they are not being captured by the virtual interface (TUN). What could be the reason for this? override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { let tunnelNetworkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "192.168.18.0") tunnelNetworkSettings.mtu=1400 let ipv4Settings = NEIPv4Settings(addresses: ["192.169.10.10"], subnetMasks: ["255.255.255.0"]) ipv4Settings.includedRoutes=[NEIPv4Route.default()] ipv4Settings.excludedRoutes = [NEIPv4Route(destinationAddress: "10.0.0.0", subnetMask: "255.0.0.0"), NEIPv4Route(destinationAddress: "172.16.0.0", subnetMask: "255.240.0.0"), NEIPv4Route(destinationAddress: "192.168.0.0", subnetMask: "255.255.0.0"), NEIPv4Route(destinationAddress:"127.0.0.0", subnetMask: "255.0.0.0"), ] tunnelNetworkSettings.ipv4Settings = ipv4Settings // Configure proxy settings let proxySettings = NEProxySettings() proxySettings.httpEnabled = true proxySettings.httpServer = NEProxyServer(address: "127.0.0.1", port: 7890) proxySettings.httpsEnabled = true proxySettings.httpsServer = NEProxyServer(address: "127.0.0.1", port: 7890) proxySettings.excludeSimpleHostnames = true proxySettings.exceptionList=["localhost","127.0.0.1"] tunnelNetworkSettings.proxySettings = proxySettings setTunnelNetworkSettings(tunnelNetworkSettings) { [weak self] error in if error != nil { completionHandler(error) return } completionHandler(nil) let stack = TUNInterface(packetFlow: self!.packetFlow) RawScoketFactory.TunnelProvider=self stack.register(stack: UDPDirectStack()) stack.register(stack: TCPDirectStack()) stack.start() } } NWUdpSession.swift // // NWUDPSocket.swift // supervpn // // Created by TobbyQuinn on 2025/2/3. // import Foundation import NetworkExtension import CocoaLumberjack public protocol NWUDPSocketDelegate: AnyObject{ func didReceive(data:Data,from:NWUDPSocket) func didCancel(socket:NWUDPSocket) } public class NWUDPSocket:NSObject{ private let session:NWUDPSession private let timeout:Int private var pendingWriteData: [Data] = [] private var writing = false private let queue:DispatchQueue=QueueFactory.getQueue() public weak var delegate:NWUDPSocketDelegate? public init?(host:String,port:UInt16,timeout:Int=Opt.UDPSocketActiveTimeout){ guard let udpSession = RawScoketFactory.TunnelProvider?.createUDPSession(to: NWHostEndpoint(hostname: host, port: "\(port)"), from: nil) else{ return nil } session = udpSession self.timeout=timeout super.init() session.addObserver(self, forKeyPath: #keyPath(NWUDPSession.state),options: [.new], context: nil) session.setReadHandler({ dataArray, error in self.queueCall{ guard error == nil, let dataArray = dataArray else { print("Error when reading from remote server or connection reset") return } for data in dataArray{ self.delegate?.didReceive(data: data, from: self) } } }, maxDatagrams: 32) } /** Send data to remote. - parameter data: The data to send. */ public func write(data: Data) { pendingWriteData.append(data) checkWrite() } public func disconnect() { session.cancel() } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard keyPath == "state" else { return } switch session.state { case .cancelled: queueCall { self.delegate?.didCancel(socket: self) } case .ready: checkWrite() default: break } } private func checkWrite() { guard session.state == .ready else { return } guard !writing else { return } guard pendingWriteData.count > 0 else { return } writing = true session.writeMultipleDatagrams(self.pendingWriteData) {_ in self.queueCall { self.writing = false self.checkWrite() } } self.pendingWriteData.removeAll(keepingCapacity: true) } private func queueCall(block:@escaping ()->Void){ queue.async { block() } } deinit{ session.removeObserver(self, forKeyPath: #keyPath(NWUDPSession.state)) } }
1
0
277
Feb ’25
Blocking Network Requests per iOS App
What I want to do? I want to completely block network traffic for installed iOS apps. Hence, I need to filter network traffic based on the app, which executes this network request. Note that my app is created for personal use and learning purposes. How is this possible on iOS. Could you kindly point me into the right direction? What I don't want to do? Block network requests just by using the given domain names or using local VPNs. What I did? I skimmed through the Network Extension documentation and this forum. https://developer.apple.com/documentation/networkextension/content-filter-providers?language=objc https://developer.apple.com/forums/thread/692597 Thank you! BR, Markus
1
0
360
Jan ’25
NEPacketTunnelProvider stopped connecting on arm macOS 14 during tests
I have tests where I connect to NEPacketTunnelProvider. I run tests with circleci and fastlane, on self hosted intel and arm macs. I updated macs from macOS 13 to macOS 14 and the tests on arm stopped connecting, while the same tests on intel kept working as usual. Moreover, I noticed the tests don't work when run from circleci and fastlane. If I cancel the job and click "connect" myself on the app that stayed hanging from the cancelled tests, the connection will succeed. But if the tests are running, the connection will fails. Running the tests from xcode succeeds too. These are the logs from the tunnel. Could you suggest me where to dig? Or maybe you can see the issue from the logs? Tunnel logs when they fail
1
0
417
Dec ’24
Local Network privacy blocking my app when it shouldn't
I have read the other most relevant posts on this topic here and here. However, the situations described in these posts are different. My app is just a regular Mach-O bundle with a single executable that is launched by the user from the Finder. I've read the Local Network Privacy FAQ and TN3179 carefully and these also doesn't cover the problem described below, which is being reported to me by several of my users. The problem is that some days after giving Local Network permission to my app, without having changed anything, local network connections will spontaneously start failing with EHOSTUNREACH, indicating that it is being blocked by macOS. This typically happens after a Mac reboot. Toggling off/on the Local Network permission for my app will get it working again, until the next time it fails. My users who are reporting this have stated that they are running macOS Sonoma 15.2, with only a single version/copy of my app installed. I've tried, and failed, to reproduce this in a VM with a clean 15.2 system, but maybe this is due to the relatively short duration of my testing (days rather than weeks). I know there isn't much to go on here, and it may be tempting to put this down to misreporting. After all, the vast majority of my users aren't reporting this, and I can't reproduce it. But, I have received enough similar reports at this point that it's starting to feel like a macOS bug. Is anyone else seeing this? If there is anything that anyone can suggest - either modifications in my app, or anything that my users can do on their side - this would be very much appreciated! Many thanks, Ben
1
0
416
Jan ’25