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)
}
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
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?
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
My app has local network permission on macOS Sequoia and works in most cases. I've noticed that after unlocking my MacBook Pro, the very first request will regularly fail with a No Route to Host. A simple retry resolves the issue, but I would have expected the very first request to succeed.
Is this is a known issue on macOS Sequoia or by design? I'd prefer not to add a retry for this particular request as the app is a network utility.
➜ ~ 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)
➜ ~
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
I'm trying to handle the error in NEHotspotConfigurationManager connection method.When i try even OS network connect dialog showing with "Cannot connect" response return as "Success".
In my flow i'm trying to connect to a private network. First i connect using below code and then set the IP Address,SubNetMask,Router and DNS server address manually to already added Wifi by running below code. I'm doing this manually because as i understand you cannot set the IP Address,SubNetMask,Router and DNS server address using Swift.
https://forums.developer.apple.com/forums/thread/96834?page=2
I read the above thread and what i can understand from that is it's a bug in the os method. So does this problem fixed on latest iOS version? or is there a way to handle this problem?
Error handler code→
let eapSetting = NEHotspotEAPSettings()
eapSetting.username = self.username
eapSetting.password = self.password
eapSetting.supportedEAPTypes = [NEHotspotEAPSettings.EAPType.EAPPEAP.rawValue as NSNumber]
eapSetting.trustedServerNames = ["ABC"]
NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: self.ssid)
let hotspotConfiguration = NEHotspotConfiguration(ssid: self.ssid, eapSettings: eapSetting)
manager.apply(hotspotConfiguration){ (error) in
if let error = error {
print("Error")
return
} else {
print("Success")
return
}
}
Hi everyone,
I am developing an application for macOS and need to monitor the network usage (bytes sent and received) of specific processes. Previously, I used the nettop command to achieve this, but I found that it leads to high CPU usage, often reaching 95%.
I'm looking for alternative methods to obtain the network usage information of processes. This could be through a different command or an available macOS API. Any suggestions or guidance on more efficient ways to gather this data would be greatly appreciated.
Thank you!
Hello,
I'd like to find out if macOS Sequoia's MAC Address randomization affects the data (specifically, MAC addresses) we receive from I/O Kit.
For context, I'd like to find out if it affects my Mac App Store receipt validation code in any way.
Thank you,
– Matthias
PLATFORM AND VERSION
iOS
Development environment: Xcode Version 16.0 (16A242d), macOS 15.0 (24A335)
Run-time configuration: macOS 15.0 (24A335)
DESCRIPTION OF PROBLEM
macOS Sequoia has new Privacy & Security requirements for local area network access. This causes a call to POSIX socket function 'sendto' to fail immediately with EHOSTUNREACH on the first execution of any app that calls it. That failure occurs even if the socket is set to block for well over the time that it would typically take for the user to click "Allow" when presented with a system dialogue box that requests new permissions for the app.
A test XCode project has been provided that is capable of reproducing the issue (see macOSsocketfail.zip at https://drive.google.com/file/d/14VxkT03ddm48RCXikLHf-aWgdqxwnpAB/view?usp=sharing). It will generate a log file that contains time-stamped messages. They report each step in the creation of a blocking UDP socket – and which system call has failed as a result of which error. The message time stamps demonstrate that macOS has terminated the sendto function call after tens of microseconds, well before the 5 minute timeout on the socket, and that it terminates with errno EHOSTUNREACH. That error is misleading, because the destination is pingable on my setup at the time of execution. The second execution of the app functions without error if "Allow" has been selected during the first run.
This specific macOS behaviour does not appear to be documented anywhere that I have yet encountered; e.g. the sendto man page, the Privacy & Security LAN FAQ, etc. It is, however, highly disruptive to the use of our product, which hinges on LAN access. We have a situation in which a relatively large collection of apps are using the same shared library to manage network access. All of them must now receive manual permission from an administrator to work; but all of them will fail on their first execution. The problem is amplified because our customers use our framework to build their own apps, and not every user is an administrator. In contrast, apps that use our framework would simply work without issue on their first execution when run on macOS versions that precede Sequoia.
We must support our software across multiple platforms, hence the reason that we are using POSIX function calls to implement networking. Unfortunately, the use of an Apple-specific networking API is not a viable solution for us.
How should we mitigate this problem? Is there some way to configure an Xcode project so that the build product will already have Sequoia LAN permissions? I have read about the com.apple.developer.networking.multicast entitlement, but it is unclear whether it will help us, from the material that is available.
STEPS TO REPRODUCE
POSIX function call sequence
For the following, addr has type struct sockaddr_in, and it is set appropriately for binding or broadcasting using standard library macros and functions. &addr is cast to a const struct sockaddr pointer and assigned to saddr.
sock = socket( PF_INET, SOCK_DGRAM , 0 ) ;
bind( sock, saddr, sizeof( addr ) ) ;
r = 1 ; setsockopt( sock, SOL_SOCKET, SO_BROADCAST, &r, sizeof( r ) );
struct timeval timeout = { 300 , 0 }; setsockopt( sock , SOL_SOCKET , SO_RCVTIMEO , &timeout , sizeof( timeout ) );
sendto( sock, msg, strlen( msg ) + 1, 0, saddr , sizeof( addr ) ) ;
Test program, presuming that a device with IP 100.1.1.1 exists on the LAN that the mac is also connected to.
Open Xcode project macOSsocketfail.
Build project.
Execute first run of macOSsocketfail.app.
Click "Allow" when asked for LAN permissions.
Search for macOSsocketfail_log.txt, and make a copy with a distinct name e.g. macOSsocketfail_log_firstrun.txt.
Execute second run of macOSsocketfail.app.
Search for macOSsocketfail_log.txt, and make a copy with a distinct name e.g. macOSsocketfail_log_secondrun.txt.
Examine log files.
The first run log file will contain the following messages (time stamping will naturally differ):
1727710614.064009: Running udptest
1727710614.064015: Creating socket
1727710614.064030: Bind socket to port: 4000
1727710614.064061: Enable socket broadcast
1727710614.064064: Set socket timeout to 300.000000sec
1727710614.064067: Attempt to send blocking UDP connection packet to 100.1.1.1:589
1727710614.064124: sendto: No route to host
Error during call to sendto: errno is EHOSTUNREACH: No route to host
The second run log file will record a different outcome:
1727713660.733431: Running udptest
1727713660.733436: Creating socket
1727713660.733451: Bind socket to port: 4000
1727713660.733476: Enable socket broadcast
1727713660.733479: Set socket timeout to 300.000000sec
1727713660.733482: Attempt to send blocking UDP connection packet to 100.1.1.1:589
1727713660.733540: Ran to completion with no error detected
Note that each line of the log files begins with a timestamp. The unit is seconds, and the resolution is to the nearest microsecond. Time values are obtained using gettimeofday().
RELEVANT LINKS
https://developer.apple.com/forums/thread/663858
https://forums.developer.apple.com/forums/thread/757824
https://developer.apple.com/forums/thread/760964
https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_networking_multicast/
https://developer.apple.com/forums/thread/657887
https://developer.apple.com/forums/thread/655920
When using rvictl, I notice that it creates 2 interfaces. One of which establishes a link local connection between the iPhone and the Mac. What is this connection for? Why is it so talkative? and why can I only bring one of the created interfaces down but not the other?
When I try to bring down the interfaces with the ifconfig enX down command it stops the DHCP requests and several TCP DUP ACK, but the other interface is persistent and will not stop talking.
Can someone explain what type of traffic is being transmitted between the Mac and the iPhone?
We have an iOS app which includes a packet tunnel provider network extension. We have noticed on rare occasions that the VPN fails to start when we try to start the VPN from the app after installing it. However, rebooting the device or reinstalling the app fixes the issue.
When creating the sysdiagnose file, we found some strange messages, a snippet is given below:
2024-09-10 13:40:20.291430 +0100 launchd Could not find and/or execute program specified by service: 2: No such file or directory: /private/var/containers/Bundle/Application/2FA92604-C67D-490D-8E8E-00F8D6FBF990/Sample.app/PlugIns/Tunnel.appex/Tunnel
error 2024-09-10 13:40:20.291456 +0100 launchd Service could not initialize: access(/private/var/containers/Bundle/Application/2FA92604-C67D-490D-8E8E-00F8D6FBF990/Sample.app/PlugIns/Tunnel.appex/Tunnel, X_OK) failed with errno 2 - No such file or directory, error 0x6f - Invalid or missing Program/ProgramArguments
We encountered this before several months ago on iOS 17.4 and reported it when the issue occurred, but this issue continues to be present in the iOS 18 release candidate.
Is there any solution for this issue?
Feedback ID: FB13714761
I am in the middle of investigating an issue arising in the call to setsockopt syscall where it returns an undocumented and unexpected errno. As part of that, I'm looking for a way to list any socket content filters or any such extensions are in play on the system where this happens.
To do that, I ran:
systemextensionsctl list
That retuns the following output:
0 extension(s)
which seems to indicate there's no filters or extensions in play.
However, when I do:
netstat -s
among other things, it shows:
net_api:
2 interface filters currently attached
2 interface filters currently attached by OS
2 interface filters attached since boot
2 interface filters attached since boot by OS
...
4 socket filters currently attached
4 socket filters currently attached by OS
4 socket filters attached since boot
4 socket filters attached since boot by OS
What would be the right command/tool/options that I could use to list all the socket filters/extensions (and their details) that are in use and applicable when a call to setsockopt is made from an application on that system?
Edit: This is on a macosx-aarch64 with various different OS versions - 13.6.7, 14.3.1 and even 14.4.1.
If we start uploading a video file from the foreground and then switch to another app or press the home button, we can enable background processing by selecting the 'Background processing' option in the app's background modes. We utilize URLSession to handle the upload. I have a few questions regarding this process:
If the user manually kills the app, will the upload continue in the background?
For files around 100 MB, if the user locks the phone while the upload is in progress (and the app is in the background but not terminated), will the upload still be successful?
Does Apple provide any additional APIs that would facilitate successful file uploads even if the user terminates the app?
I would appreciate any solutions or insights you can provide. Thank you!
I want to connect to Wi-Fi programmatically using swift in my iPad application and I want to create according to bellow flow.
Enter the network name programmatically
Set the programmatically "WAP2-Enterprise" for security.
Set username/password.
A certificate popup will appear, so tap "Trust".
"Turn on the following information." otherwise off.
Automatic connection
Restrict IP address tracking
Set the programmatically IPV4 address below.
Configure ID: Manual
IP address: 192.***.***.***
For tablets, ○○: 1 to 20
Subnet mask: 255.255.255.0
Router: 192.***.***.***
Configure DNS server(Set the programmatically)
Manual
Add server: 8.8.8.8
HTTP proxy(Set the programmatically)
Configure proxy: off
if anyone you can guide me to proper way much a appreciated!!!
I am trying to browse an SSH Service from UI Test Target using NWBrowser
let descriptor = NWBrowser.Descriptor.bonjour(type: "_superapp._tcp", domain: "local.")
let browser = NWBrowser(for: descriptor, using: .tcp)
browser.stateUpdateHandler = { newState in
print("browser.stateUpdateHandler \(newState)")
}
I get failed(-65555: NoAuth) error
nw_browser_fail_on_dns_error_locked [B1] DNSServiceBrowse failed: NoAuth(-65555)
I have added _superapp._tcp in Bonjour Services for UI Test Target Info.plist.
I have also added Local Network Permission in UI Test Target Info.plist.
Everything works fine, when I call this Bonjour service from App Target.
Doesn't work when I call this from UI Test Target.
I have some user of my App reporting that they are not able to store thread network credentials in keychain, the error they get is "Can not store frozen credentials".
I couldn't find documentation around this error message, can anyone help me with it's meaning? Why this specific credential can't be stored in keychain?
I am working on developing a Mac app that will be distributed outside of the App Store.
I have added the network extension which packaged in System Extension with packet tunnel capability.
I have created a build following these steps here: https://developer.apple.com/forums/thread/737894
based on your suggestions in my accepted post: https://developer.apple.com/forums/thread/761251
It works fine in this case when the machine has SIP disabled and systemextensionsctl developer on.
As soon as I have made changes on the machine to systemextensionsctl developer off and SIP enabled, System Extension stopped loading.
I have copied the app to the "/Applications" directory before opening it.
When I check the loading status of the system extension with the "systemextensionsctl list" command, it shows as "[validating by category]"
Am I missing something? Thanks in advance.
Hi,
Brief background on what I'm trying to achieve:
I have an IoT device that produces a HLS stream of saved videos when they are accessed through the device's broadcast hotspot. To access the hotspot, I use an NEHotspotConfiguration. When I use AVPlayer to watch the HLS stream, everything is fine! When I use a media pod (VLC) to try to consume the HLS stream, traffic goes over cellular network even though the device's host address is 192.168.1.254. I am under the impression this is ALWAYS a local network device.
I haven't spent much time digging into the code for VLC to figure out why, but when I disable cell network in my app's settings, the VLC request resolves perfectly. I have been served radio silence on their forums and issues, so I thought if there's another solution this would be the place to ask!
Is there something going on with the way iOS handles web requests to local network devices? My IoT device's hotspot never has internet access, and after reading Quinn's Extra-ordinary Networking advice (https://developer.apple.com/forums/thread/734348), I'm still lost for how I can force my request to go to the WiFi network rather than cellular...
Does anyone have any recommendations?
Thanks in advance!
In my Packet Tunnel Provider, I'm setting the NEDNSSettings to localhost as I have a local DNS server listening on port 53 (this is a dns forwarder which conditionally forwards to different upstreams based on rules).
On iOS it works just fine, I'm able to listen on localhost:53 in the Network Extension, then set NEDNSSettings servers to "127.0.0.1".
However on macOS due to the port being under 1024, I get a Permission denied OS code 13 error. I'm assuming this is due to the Network Extension not running as root. Can this be changed?
This could be rectified if you could customize the port in NEDNSSettings, as the listener could be on port 5353, but it doesn't look like it is possible?
Just wondering if there is some other way to accomplish what I'm trying to do in the macOS Network Extension?