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?
Networking
RSS for tagExplore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.
Post
Replies
Boosts
Views
Activity
NETransparentProxyProvider having these two methods:
override func handleNewFlow(_ flow: NEAppProxyFlow) -> Bool
override func handleNewUDPFlow(
_ flow: NEAppProxyUDPFlow,
initialRemoteEndpoint remoteEndpoint: NWEndpoint
) -> Bool
During initial days when NETransparentProxyProvider was introduced,
We used handleNewFlow to handle NEAppProxyTCPFlow and handleNewUDPFlow to handle NEAppProxyUDPFlow .
Since handleNewUDPFlow is now deprecated, is it just okay to use handleNewFlow to handle both NEAppProxyTCPFlow & NEAppProxyUDPFlow?
will this works always or there are some scenario where keeping handleNewUDPFlow will be usefull?
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.
I'm trying to create a network extension packaged as a system extension on macOS,
let request = OSSystemExtensionRequest.activationRequest(forExtensionWithIdentifier: "com.example.Desktop.PacketTunnelDesktop",
queue: DispatchQueue.main)
request.delegate = delegate
// Submit the request to the system.
let extensionManager = OSSystemExtensionManager.shared
extensionManager.submitRequest(request)
The application is installed in /Applications, I have also turned off SIP and systemextensionsctl developer on
I'm not getting any breakpoint hits on my request delegate, but I am getting some logs in the console app:
making activation decision for extension with teamID teamID("XXXXXX"), identifier com.example.Desktop.PacketTunnelDesktop
no related kext found for sysex `com.example.Desktop.PacketTunnelDesktop`
extension XXXXXXX com.example.Desktop.PacketTunnelDesktop (1.0/1) advancing state from validating to validating_by_category
validate: category: com.apple.system_extension.network_extension, extension: com.example.Desktop.PacketTunnelDesktop
waiting for external validation of extension with identifier com.example.Desktop.PacketTunnelDesktop
It seems to stop here, and running systemsextensionsctl list shows:
[validating by category] as the status.
I'm trying to find some barebones example code for a network extension packaged as system extension but couldn't find any. Any ideas where to go from here?
When our app makes an API call to our backend service, we want the app to provide a client certificate in the call.
What API and mechanism we can use so that our app (iOS app store, and Mac with Developer ID) to read a client certificate present in the Keychain.
Please note that the client certificate will be put in the Keychain by an external MDM process. Not sure if an iOS or Mac app can read client certificates from Keychain which they have not put it there in the first place.
Hello Everyone,
I have developed an iOS/iPadOS app in which I am checking if the device is connected to a particular WiFi network. I am able to check that using the CNCopyCurrentNetworkInfo dictionary and the value of the key "kCNNetworkInfoKeySSID".
So, while doing that I was wondering what will happen if there is another WiFi network with same SSID.
Is there another way to identify a WiFi network uniquely?
Hi,
We are building a VPN application with a packet tunnel network extension.
The NE (network extension) provides the VPN itself (obviously) alongside some VPN related functionalities.
The VPN does not intends to capture all the network, instead it just give access to one or several remote network (aka we are only routing some subnet to the NE).
The issue is that for some functionalities, we would need the NE to create network connection that might need to be routed through the tunnel.
The issue is that the routes that we declared with the NE are not applied to the network traffic emanating from the NE itself.
I do understand that this is a requirement to avoid VPN loop, moreover with VPN that capture all the traffic. But in our case we know we will avoid collision since we only route some networks.
What solution do we have ?
Is there an option somewhere to for the application of all route to the NE ?
Hello Team,
I want to know if there's a way to uninstall System Extension without prompting the user for authorisation.
These are ways I found to uninstall System Extension
The deactivationRequest api prompts the user for uninstalling System extension.
If I use Apple script to drag and drop the application[which is embedded with System Extension] to trash also prompts the user.
The only workaround that doesn't prompt is by disabling SIP and using the systemextensionsctl uninstall command.
I want to know if there's any other solution that can uninstall System Extension without prompting the user for authorisation.
Thanks!
Hi,
We are currently working on porting our PacketTunnelProvider app extension to run as a system extension. Things are mostly working great, but we're now testing upgrades from the existing app extension to a system extension.
We have an existing configuration that gets created and runs perfectly fine with the app extension. Then, when we go and upgrade to the system extension, and attempt to connect using the same existing configuration.
We see this error in the nesessionmanager logs:
10:00:57.717694-0700 nesessionmanager Signature check failed: code failed to satisfy specified code requirement(s) error
10:00:57.717914-0700 nesessionmanager Rejecting agent com.agentBundleID.bundleID because it does not satisfy the code signature requirements error
10:00:57.717937-0700 nesessionmanager Failed to launch com.agentBundleID.bundleID
If we create a new configuration profile in our upgraded app w/system extension it works fine. The problem only occurs with existing profiles.
Our app doesn't even get any notification about this error,
startVPNTunnelWithOptions:andReturnError: doesn't return any error that we can work with.
My gut tells me this has to do with the ProviderDesignatedRequirement not being correct, but I really have no way to confirm this at all. The NETunnelProviderProtocol has no way to specify that in its API. Our providerBundleIdentifier was unchanged between the two extensions.
Is there anything that we can do here? Or are we stuck re-creating the configuration profile after an upgrade?
I am developing an app designed for use in hospital environments where public internet access may not be available. The app consists of two parts: the main app and a Local Connectivity Extension. Both components rely on socket connections (TCP and UDP) to maintain communication with a server.
We have observed consistent disconnections occurring every 1-2 hours when app in the foreground (both extension and app), and would like to clarify Apple's guidelines regarding long-term socket connections. Specifically, is it permissible to keep a continuous socket connection (both TCP and UDP) active for an extended period? If so, are there any restrictions or best practices we should follow to ensure stable connectivity?
Thank you for your assistance.
I’m seeking clarification on why iOS prioritizes IPv6 when both IPv4 and IPv6 are available. Does iOS always default to using IPv6 in such scenarios? Is this happening by design as Apple developer docs never explicitly state the prioritization rules.
This might explain us why the issue doesn’t occur as frequently in IPv4-only environments
In macOS 15 Sequoia (tested on 15.0 and 15.0.1), the icon of our network extension (and of other third party apps) is missing. See the attached screenshot, instead of the generic app icon there should be the icon of our app.
Is this a bug, or is there something we developers can/should do? I tried adding an asset catalog with the app icon, and specifying that using ASSETCATALOG_COMPILER_APPICON_NAME like we do in the main app. Even though the icon is added to the Resources folder of our .systemextension, and is referenced in the Info.plist using CFBundleIconFile and CFBundleIconName, the icon is still not showing in the System Settings.
Hello everyone I'm new to swift and I can't quite figure it out yet:(
I am developing a simple online game for mac os that involves two players connected to the same WIFI. I need to constantly receive information from the server and I don't understand how to implement it. If I call the receive function indefinitely, then my program freezes. I realized that this should happen asynchronously, but that's just how my program understands when a package came from the server. I understand that I need a delegate or handler, but I don't understand how to do it. Please help me to add the receive function and everything that is necessary for it
import Foundation
import Network
enum CustomErrors: Error {
case DataError
case NetworkError
case DecoderError
case InvalidAddress
}
class TapperConnection: ObservableObject {
private var _serverAlive = false
private var connection: NWConnection!
private var serverPort: UInt16 = 20001
private var serverIp: String = "127.0.0.1"
private var _myDeviceName = Host.current().localizedName ?? ""
@Published var messageDc: [HostData] = []
@Published var messageLobby: [HostData] = []
@Published var messageState: GameData = GameData()
private var buffer = 2048
private var _inputData = ""
private var _outputData = ""
private var _myIp = ""
private var isServer = false
private var isClient = false
var myIp: String {
return _myIp
}
var myDeviceName: String {
return _myDeviceName
}
private func getMyIp() -> String? {
var address: String?
var ifaddr: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil }
guard let firstAddr = ifaddr else { return nil }
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
let name = String(cString: interface.ifa_name)
if name == "en0" || name == "en2" || name == "en3" || name == "en4" || name == "pdp_ip0" || name == "pdp_ip1" || name == "pdp_ip2" || name == "pdp_ip3" {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
return address
}
private func isValidIP(_ ip: String) -> Bool {
let regex = try! NSRegularExpression(pattern: "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
return regex.firstMatch(in: ip, range: NSRange(location: 0, length: ip.utf16.count)) != nil
}
@Sendable
private func updateServerState(to state: NWConnection.State) {
switch state {
case .setup:
_serverAlive = true
case .waiting:
_serverAlive = true
case .ready:
_serverAlive = true
case .failed:
_serverAlive = false
case .cancelled:
_serverAlive = false
case .preparing:
_serverAlive = false
default:
_serverAlive = false
}
}
func createConnection() throws {
let ip = getMyIp()
if ip != nil {
serverIp = ip!
_myIp = ip!
} else {
throw CustomErrors.NetworkError
}
isServer = true
do {
try connectToServer()
} catch {
throw CustomErrors.NetworkError
}
}
func createConnection(ip: String) throws {
if isValidIP(ip) {
serverIp = ip
} else {
throw CustomErrors.InvalidAddress
}
let _ip = getMyIp()
if _ip != nil {
_myIp = _ip!
} else {
throw CustomErrors.NetworkError
}
isClient = true
do {
try connectToServer()
} catch {
throw CustomErrors.NetworkError
}
}
private func connectToServer() throws {
if isServer {
// ...............
// run server exec
// ...............
}
let _params = NWParameters(dtls: nil, udp: .init())
_params.requiredLocalEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host(_myIp), port: 20002)
connection = NWConnection(host: NWEndpoint.Host(serverIp), port: NWEndpoint.Port(rawValue: serverPort)!, using: _params)
connection.stateUpdateHandler = updateServerState(to:)
connection.start(queue: .global())
while !_serverAlive {}
do {
try send(message: "im:\(_myDeviceName)")
receive()
} catch {
print("Error sending disconnect message: \(error)")
}
}
func closeConnection() {
do {
try send(message: "dc:\(_myDeviceName)")
} catch {
print("Error sending disconnect message: \(error)")
}
_serverAlive = false
connection.cancel()
}
func send(message: String) throws {
var error = false
connection.send(content: message.data(using: String.Encoding.utf8), completion: NWConnection.SendCompletion.contentProcessed(({ NWError in
if NWError == nil {
print("Data was sent!")
} else {
error = true
}
})))
if error {
throw CustomErrors.NetworkError
}
}
func receive() {
self.connection.receive(minimumIncompleteLength: 1, maximumLength: 65535) { data, _, isComplete, _ in
if isComplete {
if data != nil {
let response: String = String(decoding: data!, as: UTF8.self)
var decodeData: Any
var messageType: MessageType
(decodeData, messageType) = try! Decoder.decodeMessage(response)
switch messageType {
case MessageType.lobby:
self.messageLobby = decodeData as! [HostData]
case MessageType.state:
self.messageState = decodeData as! GameData
case MessageType.dc:
self.messageDc = decodeData as! [HostData]
}
}
self.receive()
}
}
}
}
I am developing an application that allows you to interact with people on your local network.
I have a view called ProfileView() which has has identifiers inside of it such as that build up the profile for each person.
Essentially, what I want to do is discover people who are on this app on your local network, or who are nearby to you based on bluetooth. I do not want to use a server, as I would like this to be an application that does not require internet access to function. Also if possible, I would like a toggle to allow yourself to be discovered in the background, even if not using the app.
Any ideas how to do this? Also, is there any better way to do this instead of Bluetooth and Local Network?
Thank you
Possible code chunks needed:
Discover nearby bluetooth users
Discover nearby network users
Toggle for discovery
Toggle for background discovery (while not using app)
Share profile (mainly just text and a profile image)
Let's say you want to stop a server.
https://developer.apple.com/forums/thread/75997
From searching apparently, there's an automatic cooldown. Don't know whether it's true or not.
That thread mentions socket variables, that I don't believe can be used with the NW stuff.
NWListener "cancel" doesn't seem to stop a server? Eitherways, doing that and trying to use .start and something like
self.listener = try NWListener(using: self.cfg_nwParameters, on: self.port)
self.listener?.start(queue: .main)
this will trigger Address already in use if you "stopped" a server, because apparently you can't stop a server with NWListener. Because the socket isn't actually closing apparently.
Hi,
Is it possible to get NEDNSSettings to enable for only .wifi or only .cellular?
I tried using interfaceTypeMatch = .wifi standalone and I also tried it together with a NEEvaluateConnectionRule matching all domains but it skips using the EDNSSettings also on .cellular even if .interfaceTypeMatch is .wifi.
This is the more advanced example of the two and it seems to not care about the interfaceTypeMatch flag:
let evaluateRule = NEEvaluateConnectionRule(matchDomains: [], andAction: .neverConnect)
let evaluateConnectionRule = NEOnDemandRuleEvaluateConnection()
evaluateConnectionRule.connectionRules = [evaluateRule]
evaluateConnectionRule.interfaceTypeMatch = .wiFi
self.dnsManager.onDemandRules = [evaluateConnectionRule]
Should this be possible or does it only work with VPN?
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)
}
Are there any known memory leaks in the Network framework? When using the start function on NWConnection I find a small leak appear every time (see attached image). I am using it for websockets
Hi,
I have a hardware device that asks as an ethernet server.
I need to connect to it using a TCP socket over ethernet.
Problem is, I cannot find an API or example code on how to go about this. I have tried to search through the available network interfaces using AF_LINK (link layer) family but only the wifi shows up (en0), even when the device is connected and the iPhone self-assigns an IP etc.
Extra challenge is, I am using objective C because all of my other code is written that way. I'm happy to add a swift module where that is the only option.
Can someone please point me in the right direction?
Hello, we have encountered some issues related to calling WiFi connection APIs in our app. The code is as follows:
let ssid = "some-wifi-ap"
let password = "some-pw"
let config: NEHotspotConfiguration = NEHotspotConfiguration(ssid: ssid, passphrase: password, isWEP: false)
NEHotspotConfigurationManager.shared.apply(config, completionHandler: { (error) in
// do something
})
Question 1:
After calling the NEHotspotConfigurationManager.shared.apply method, ignoring the time it takes for the user to authorize the WiFi connection, this method takes about 4 to 10 seconds to receive a callback. Sometimes it may take even longer! Why does this method take so long to get a result callback? Are there any ways to reduce the time taken by this method? For example, optimizing the API call or the target WiFi.
Question 2:
After calling the NEHotspotConfigurationManager.shared.apply method, there is about a 3% to 5% chance of an "Unable to join the network" popup. Then, by calling NEHotspotConfigurationManager.shared.apply again, in most cases, the WiFi connection is successful. Through some stress testing, we collected some device logs, and by examining the WiFi-related logs, we found two main types of errors that might cause this "Unable to join the network" popup. The errors are as follows:
a. (Scan request failed (-528350142, Family Scan Busy)!)
b. (Error: posting APPLE80211_M_SCAN_DONE with err -536870165)(__WiFiDeviceManagerForcedAssociationCallback: failed to association error 1)
c、__WiFiDeviceManagerForcedAssociationCallback: failed to association error 2
Could you please explain in more detail the specific reasons for these two errors? We would also like to know what specific situations could cause the "Unable to join the network" popup and whether there are ways to avoid or reduce the frequency of this abnormal condition.
Additionally, the WiFi we are connecting to is an AP hotspot provided by our company's product camera without DNS service