I'm attempting to create a service that:
Listens on iOS device A using NWListener
Broadcasts the NWService ( using NWListener(service:using:)) ) on Bonjour
Allows a separate device, iOS device B, to receive information about that service via an NWBrowser
Connect to that service using the information contained in NWBrowser.Result 's NWEndpoint
I've been able to successfully do this using a SwiftNIO service, in the following environments:
iOS device A and iOS device B are physical iOS devices on the same WiFi network. This works.
iOS device A and iOS device B are iOS simulators on the same machine. This works.
iOS device A is a physical device, and iOS device B is a simulator. iOS device A is not connected to a WiFi network, iOS device B is connected to a WiFi network. This works.
However, when iOS device A and iOS device B are physical devices that are not connected to a WiFi network, I encounter the following behavior:
The Bonjour service is correctly advertised, and iOS device A and iOS device B are able to observe the advertisement of the service.
In both cases, iOS device A and iOS device B, while able to resolve an NWEndpoint for the Bonjour service, are not able to connect to each other, and the connection attempt hangs.
My setup for the listener side of things looks roughly like:
let opts: NWParameters = .tcp
opts.includePeerToPeer = true
opts.allowLocalEndpointReuse = true
let service = NWListener.Service(name: "aux", type: BONJOUR_SERVICE_TYPE, domain: "")
try bootstrap.withNWListener(NWListener(service: service, using: opts)).wait() // bootstrap is an artifact of using SwiftNIO
Similarly, my setup on the discovery side of things looks like:
let params: NWParameters = .tcp
params.includePeerToPeer = true
let browser = NWBrowser(for: .bonjour(type: BONJOUR_SERVICE_TYPE, domain: BONJOUR_SERVICE_DOMAIN), using: params)
browser.browseResultsChangedHandler = { (searchResults, changed) in
// save the result to pass on its NWEndpoint later
}
and finally, where I have an NWEndpoint, I use SwiftNIO's NIOTSConnectionBootstrap.connect(endpoint:) to initialize a connection to my TCP service ( a web socket server ).
The fact that I am able to get P2P networking (presumably over an awdl interface?) between the simulator and the iOS device suggests to me that I haven't done anything obviously wrong in my setup. Similarly, the fact that it works over the same WiFi network and that, in P2P, I am able to at least observe the Bonjour advertisement, strikes me that I'm somewhere in the right neighborhood of getting this to work. I've also ensured that my Info.plist for the app has a NSLocalNetworkUsageDescription and NSBonjourServices for the Bonjour service type I'm browsing for.
I've even attempted to exercise the "Local Network Permission" dialog by using a hacky attempt that sends data to a local IP in order to trigger a permissions dialog, though the hack does not appear to actually force the dialog to appear.
Is there some trick or other piece of knowledge regarding allowing the use of P2P w/ Network.framework and TCP connections to services?
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
On iOS 16.0, I added accessories via the MTRDeviceController class in the Matter.framework, and it worked fine.
But when I will phone upgrade to the latest version of the iOS (iOS 16.1.1), after I call "MTRDeviceController" class "pairDevice: onboardingPayload: error:" method. I get an error like this:
CHIP: [BLE] BLE:Error writing Characteristics in Chip service on the device: [The specified UUID is not allowed for this operation.]
According to the error message, I guess that the characteristics of a certain Bluetooth cannot be read and written. After trying to verify it, I find that the characteristics uuid of the Matter accessory: "18EE2EF5-263D-4559-959F-4F9C429F9D12" cannot be read.
So, my question is what can I do in iOS 16.1.1 to make my app work as well as it does on iOS 16.0.
This is happening Mac M1 Monterey OS .Environment supports both IPv4 and IPV6.
When a http client calls gettaddrinfo() it is returning both IPv6,IPv4 IPs . first v6 IPs and then v4 IPs.
We need to have a way to sort gettaddrinfo() output to get v4 ip first and then v6.
We tried changing DNS order with scutil by putting v4 DNS first , but still getaddrInfo() listing v6 IPs first .
In linux there is a way to control gettaddrinfo() o/p with /etc/gai.conf https://man7.org/linux/man-pages/man5/gai.conf.5.html . In Mac I did not find any option like this , scutil changing order DNS is not effective . can you tell us what is way to do this in MAC OSx ?
This issue has cropped up many times here on DevForums. Someone recently opened a DTS tech support incident about it, and I used that as an opportunity to post a definitive response here.
If you have questions or comments about this, start a new thread and tag it with Network so that I see it.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
iOS Network Signal Strength
The iOS SDK has no general-purpose API that returns Wi-Fi or cellular signal strength in real time. Given that this has been the case for more than 10 years, it’s safe to assume that it’s not an accidental omission but a deliberate design choice.
For information about the Wi-Fi APIs that are available on iOS, see TN3111 iOS Wi-Fi API overview.
Network performance
Most folks who ask about this are trying to use the signal strength to estimate network performance. This is a technique that I specifically recommend against. That’s because it produces both false positives and false negatives:
The network signal might be weak and yet your app has excellent connectivity. For example, an iOS device on stage at WWDC might have terrible WWAN and Wi-Fi signal but that doesn’t matter because it’s connected to the Ethernet.
The network signal might be strong and yet your app has very poor connectivity. For example, if you’re on a train, Wi-Fi signal might be strong in each carriage but the overall connection to the Internet is poor because it’s provided by a single over-stretched WWAN.
The only good way to determine whether connectivity is good is to run a network request and see how it performs. If you’re issuing a lot of requests, use the performance of those requests to build a running estimate of how well the network is doing. Indeed, Apple practices what we preach here: This is exactly how HTTP Live Streaming works.
Keep in mind that network performance can change from moment to moment. The user’s train might enter or leave a tunnel, the user might walk into a lift, and so on. If you build code to estimate the network performance, make sure it reacts to such changes.
But what about this code I found on the ’net?
Over the years various folks have used various unsupported techniques to get around this limitation. If you find code on the ’net that, say, uses KVC to read undocumented properties, or grovels through system logs, or walks the view hierarchy of the status bar, don’t use it. Such techniques are unsupported and, assuming they haven’t broken yet, are likely to break in the future.
But what about Hotspot Helper?
Hotspot Helper does have an API to read Wi-Fi signal strength, namely, the signalStrength property. However, this is not a general-purpose API. Like the rest of Hotspot Helper, this is tied to the specific use case for which it was designed. This value only updates in real time for networks that your hotspot helper is managing, as indicated by the isChosenHelper property.
But what about MetricKit?
MetricKit is so cool. Amongst other things, it supports the MXCellularConditionMetric payload, which holds a summary of the cellular conditions while your app was running. However, this is not a real-time signal strength value.
But what if I’m working for a carrier?
This post is about APIs in the iOS SDK. If you’re working for a carrier, discuss your requirements with your carrier’s contact at Apple.
I can build the SimpleFirewall application (https://developer.apple.com/documentation/networkextension/filtering_network_traffic ) using xcode:
After I run the application, seems can't block any traffic.
I find there is some logs from network extension process:
networkd_settings_read_from_file Sandbox is preventing this process from reading networkd settings file at "/Library/Preferences/com.apple.networkd.plist", please add an exception.
Any step I am missing ?
Hello, I am getting crashes on iOS 16 devices only regarding CFNetwork. Below is the full crash report. I am not able to reproduce it on my end. I've attached the .txt crash log below and also posted it below.
CFNetworkCrashLog.txt
Any help is appreciated, thank you!
Crashed: com.apple.NSXPCConnection.m-user.com.apple.nsurlsessiond
EXC_BREAKPOINT 0x00000001cfbbecec
7 Foundation 0x42054 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212
8 Foundation 0x41f3c -[NSRunLoop(NSRunLoop) runUntilDate:] + 64
9 UIKitCore 0x4d66a4 -[UIEventFetcher threadMain] + 436
10 Foundation 0x5b518 __NSThread__start__ + 716
11 libsystem_pthread.dylib 0x16cc _pthread_start + 148
12 libsystem_pthread.dylib 0xba4 thread_start + 8
com.google.firebase.crashlytics.MachExceptionServer
0 App 0x387cfc FIRCLSProcessRecordAllThreads + 393 (FIRCLSProcess.c:393)
1 App 0x3880dc FIRCLSProcessRecordAllThreads + 424 (FIRCLSProcess.c:424)
2 App 0x395be0 FIRCLSHandler + 34 (FIRCLSHandler.m:34)
3 App 0x396400 FIRCLSMachExceptionServer + 521 (FIRCLSMachException.c:521)
4 libsystem_pthread.dylib 0x16cc _pthread_start + 148
5 libsystem_pthread.dylib 0xba4 thread_start + 8
GAIThread
0 libsystem_kernel.dylib 0xda8 mach_msg2_trap + 8
1 libsystem_kernel.dylib 0x13a1c mach_msg2_internal + 80
2 libsystem_kernel.dylib 0x13c5c mach_msg_overwrite + 388
3 libsystem_kernel.dylib 0x12ec mach_msg + 24
4 CoreFoundation 0x7aac4 __CFRunLoopServiceMachPort + 160
5 CoreFoundation 0x7bd08 __CFRunLoopRun + 1232
6 CoreFoundation 0x80eb0 CFRunLoopRunSpecific + 612
7 Foundation 0x42054 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212
8 Foundation 0x41ee8 -[NSRunLoop(NSRunLoop) run] + 64
9 App 0x563d00 +[GAI threadMain:] + 64
10 Foundation 0x5b518 __NSThread__start__ + 716
11 libsystem_pthread.dylib 0x16cc _pthread_start + 148
12 libsystem_pthread.dylib 0xba4 thread_start + 8
com.apple.NSURLConnectionLoader
0 libsystem_kernel.dylib 0xda8 mach_msg2_trap + 8
1 libsystem_kernel.dylib 0x13a1c mach_msg2_internal + 80
2 libsystem_kernel.dylib 0x13c5c mach_msg_overwrite + 388
3 libsystem_kernel.dylib 0x12ec mach_msg + 24
4 CoreFoundation 0x7aac4 __CFRunLoopServiceMachPort + 160
5 CoreFoundation 0x7bd08 __CFRunLoopRun + 1232
6 CoreFoundation 0x80eb0 CFRunLoopRunSpecific + 612
7 CFNetwork 0x257ff0 _CFURLStorageSessionDisableCache + 61088
8 Foundation 0x5b518 __NSThread__start__ + 716
9 libsystem_pthread.dylib 0x16cc _pthread_start + 148
10 libsystem_pthread.dylib 0xba4 thread_start + 8
CommandHandler
0 libsystem_kernel.dylib 0xda8 mach_msg2_trap + 8
1 libsystem_kernel.dylib 0x13a1c mach_msg2_internal + 80
2 libsystem_kernel.dylib 0x13c5c mach_msg_overwrite + 388
3 libsystem_kernel.dylib 0x12ec mach_msg + 24
4 CaptiveNetwork 0x9d78 ConnectionGetCommandInfo + 160
5 CaptiveNetwork 0x7c54 __add_signal_port_source_block_invoke_2 + 244
6 libdispatch.dylib 0x3f88 _dispatch_client_callout + 20
7 libdispatch.dylib 0x7418 _dispatch_continuation_pop + 504
8 libdispatch.dylib 0x1aa58 _dispatch_source_invoke + 1588
9 libdispatch.dylib 0xb518 _dispatch_lane_serial_drain + 376
10 libdispatch.dylib 0xc18c _dispatch_lane_invoke + 384
11 libdispatch.dylib 0x16e10 _dispatch_workloop_worker_thread + 652
12 libsystem_pthread.dylib 0xdf8 _pthread_wqthread + 288
13 libsystem_pthread.dylib 0xb98 start_wqthread + 8
Thread
0 libsystem_kernel.dylib 0x12b0 __workq_kernreturn + 8
1 libsystem_pthread.dylib 0xe44 _pthread_wqthread + 364
2 libsystem_pthread.dylib 0xb98 start_wqthread + 8
Thread
0 libsystem_pthread.dylib 0xb90 start_wqthread + 254
Crashed: com.apple.NSXPCConnection.m-user.com.apple.nsurlsessiond
0 libobjc.A.dylib 0x6cec objc_opt_respondsToSelector + 48
1 libsystem_trace.dylib 0x6480 _os_log_fmt_flatten_object + 248
2 libsystem_trace.dylib 0x41a0 _os_log_impl_flatten_and_send + 1864
3 libsystem_trace.dylib 0x21bc _os_log + 152
4 libsystem_trace.dylib 0x7840 _os_log_impl + 24
5 CFNetwork 0x10dc08 _CFURLConnectionCopyTimingData + 34880
6 Foundation 0x64b620 message_handler_error + 360
7 libxpc.dylib 0x1179c _xpc_connection_call_event_handler + 152
8 libxpc.dylib 0x11be8 _xpc_connection_mach_event + 1020
9 libdispatch.dylib 0x4048 _dispatch_client_callout4 + 20
10 libdispatch.dylib 0x24104 _dispatch_mach_cancel_invoke + 128
11 libdispatch.dylib 0x21720 _dispatch_mach_invoke + 916
12 libdispatch.dylib 0xb518 _dispatch_lane_serial_drain + 376
13 libdispatch.dylib 0xc1c0 _dispatch_lane_invoke + 436
14 libdispatch.dylib 0x16e10 _dispatch_workloop_worker_thread + 652
15 libsystem_pthread.dylib 0xdf8 _pthread_wqthread + 288
16 libsystem_pthread.dylib 0xb98 start_wqthread + 8
We have been observing an issue where when binding a UDP socket to an ephemeral port (i.e. port 0), the OS ends up allocating a port which is already bound and in-use. We have been seeing this issue across all macos versions we have access to (10.x through recent released 13.x).
Specifically, we (or some other process) create a udp4 socket bound to wildcard and ephemeral port. Then our program attempts a bind on a udp46 socket with ephemeral port. The OS binds this socket to an already in use port, for example you can see this netstat output when that happens:
netstat -anv -p udp | grep 51630
udp46 0 0 *.51630 *.* 786896 9216 89318 0 00000 00000000 00000000001546eb 00000000 00000800 1 0 000001
udp4 0 0 *.51630 *.* 786896 9216 89318 0 00000 00000000 0000000000153d9d 00000000 00000800 1 0 000001
51630 is the (OS allocated) port here, which as you can see has been allocated to 2 sockets. The process id in this case is the same (because we ran an explicit reproducer to reproduce this), but it isn't always the case.
We have a reproducer which consistenly shows this behaviour. Before filing a feedback assistant issue, I wanted to check if this indeed appears to be an issue or if we are missing something here, since this appears to be a very basic thing.
Hello,
Our users are seeing random crashes in our packet filter system extension on macOS. Any help pointing me in the right direction to either avoid the issue or fix it would be greatly appreciated. Attached is the crash log.
Thank you.
packetfilter.crash
Crashed Thread: 2 Dispatch queue: com.apple.network.connections
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000112918700
Exception Note: EXC_CORPSE_NOTIFY
Termination Signal: Bus error: 10
Termination Reason: Namespace SIGNAL, Code 0xa
Terminating Process: exc handler [40687]
...
Thread 2 Crashed:: Dispatch queue: com.apple.network.connections
0 libsystem_kernel.dylib 0x00007fff2089b46e os_channel_get_next_slot + 230
1 com.apple.NetworkExtension 0x00007fff2e2e2643 __40-[NEFilterPacketInterpose createChannel]_block_invoke + 560
2 libdispatch.dylib 0x00007fff20718806 _dispatch_client_callout + 8
3 libdispatch.dylib 0x00007fff2071b1b0 _dispatch_continuation_pop + 423
4 libdispatch.dylib 0x00007fff2072b564 _dispatch_source_invoke + 2061
5 libdispatch.dylib 0x00007fff20720318 _dispatch_workloop_invoke + 1784
6 libdispatch.dylib 0x00007fff20728c0d _dispatch_workloop_worker_thread + 811
7 libsystem_pthread.dylib 0x00007fff208bf45d _pthread_wqthread + 314
8 libsystem_pthread.dylib 0x00007fff208be42f start_wqthread + 15
In our PacketTunnelProvider we are seeing behavior for enforceRoutes which appears to contradict the documentation.
According to the developer documentation (my emphasis):
If this property is YES when the includeAllNetworks property is NO, the system scopes the included routes to the VPN and the excluded routes to the current primary network interface.
If we set these IPv4 settings:
IPv4Settings = {
configMethod = manual
addresses = (
172.16.1.1,
)
subnetMasks = (
255.255.255.255,
)
includedRoutes = (
{
destinationAddress = 0.0.0.0
destinationSubnetMask = 0.0.0.0
},
)
excludedRoutes = (
{
destinationAddress = 10.10.0.0
destinationSubnetMask = 255.255.255.0
},
)
overridePrimary = YES
}
Then if enforceRoutes is set to YES, then we do not see traffic for the excluded network, which is the expected behavior. If enforceRoutes is set to NO, then we do see traffic for the excluded network.
In both cases includeAllNetworks and excludeLocalNetworks are both NO.
The excluded network is not one of the local LANs.
Is this a known issue? Is there some documented interaction that I missed here?
Is there a workaround we can use to make this function as intended, with enforceRoutes set to YES?
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!!!
Most apps perform ordinary network operations, like fetching an HTTP resource with URLSession and opening a TCP connection to a mail server with Network framework. These operations are not without their challenges, but they’re the well-trodden path.
Note If your app performs ordinary networking, see TN3151 Choosing the right networking API for recommendations as to where to start.
Some apps have extra-ordinary networking requirements. For example, apps that:
Help the user configure a Wi-Fi accessory
Require a connection to run over a specific interface
Listen for incoming connections
Building such an app is tricky because:
Networking is hard in general.
Apple devices support very dynamic networking, and your app has to work well in whatever environment it’s running in.
Documentation for the APIs you need is tucked away in man pages and doc comments.
In many cases you have to assemble these APIs in creative ways.
If you’re developing an app with extra-ordinary networking requirements, this post is for you.
Note If you have questions or comments about any of the topics discussed here, put them in a new thread here on DevForums. Make sure I see it by tagging it with… well… tags appropriate to the specific technology you’re using, like Foundation, CFNetwork, Network, or Network Extension.
Links, Links, and More Links
Each topic is covered in a separate post:
The iOS Wi-Fi Lifecycle describes how iOS joins and leaves Wi-Fi networks. Understanding this is especially important if you’re building an app that works with a Wi-Fi accessory.
Network Interface Concepts explains how Apple platforms manage network interfaces. If you’ve got this far, you definitely want to read this.
Network Interface Techniques offers a high-level overview of some of the more common techniques you need when working with network interfaces.
Network Interface APIs describes APIs and core techniques for working with network interfaces. It’s referenced by many other posts.
Running an HTTP Request over WWAN explains why most apps should not force an HTTP request to run over WWAN, what they should do instead, and what to do if you really need that behaviour.
If you’re building an iOS app with an embedded network server, see Showing Connection Information in an iOS Server for details on how to get the information to show to your user so they can connect to your server.
Many folks run into trouble when they try to find the device’s IP address, or other seemingly simple things, like the name of the Wi-Fi interface. Don’t Try to Get the Device’s IP Address explains why these problems are hard, and offers alternative approaches that function correctly in all network environments.
If you’re building an app that works with a Wi-Fi accessory, see Working with a Wi-Fi Accessory.
If you’re trying to gather network interface statistics, see Network Interface Statistics.
There are also some posts that are not part of this series but likely to be of interest if you’re working in this space:
Local Network Privacy FAQ discusses iOS’s local network privacy feature.
Calling BSD Sockets from Swift does what it says on the tin, that is, explain how to call BSD Sockets from Swift. When doing weird things with the network, you often find yourself having to use BSD Sockets, and that API is not easy to call from Swift. The code therein is primarily for the benefit of test projects, oh, and DevForums posts like this one.
TN3111 iOS Wi-Fi API overview is a critical resource if you’re doing Wi-Fi specific stuff on iOS.
TLS For Accessory Developers tackles the tricky topic of how to communicate securely with a network-based accessory.
Networking Resources has links to many other useful resources.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Revision History
2024-04-30 Added a link to Network Interface Statistics.
2023-09-14 Added a link to TLS For Accessory Developers.
2023-07-23 First posted.
For important background information, read Extra-ordinary Networking before reading this.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Working with a Wi-Fi Accessory
Building an app that works with a Wi-Fi accessory presents specific challenges. This post discusses those challenges and some recommendations for how to address them.
Note While my focus here is iOS, much of the info in this post applies to all Apple platforms.
IMPORTANT iOS 18 introduced AccessorySetupKit, a framework to simplify the discovery and configuration of an accessory. I’m not fully up to speed on that framework myself, but I encourage you to watch WWDC 2024 Session 10203 Meet AccessorySetupKit and read the framework documentation.
Accessory Categories
I classify Wi-Fi accessories into three different categories.
A bound accessory is ultimately intended to join the user’s Wi-Fi network. It may publish its own Wi-Fi network during the setup process, but the goal of that process is to get the accessory on to the existing network. Once that’s done, your app interacts with the accessory using ordinary networking APIs.
An example of a bound accessory is a Wi-Fi capable printer.
A stand-alone accessory publishes a Wi-Fi network at all times. An iOS device joins that network so that your app can interact with it. The accessory never provides access to the wider Internet.
An example of a stand-alone accessory is a video camera that users take with them into the field. You might want to write an app that joins the camera’s network and downloads footage from it.
A gateway accessory is one that publishes a Wi-Fi network that provides access to the wider Internet. Your app might need to interact with the accessory during the setup process, but after that it’s useful as is.
An example of this is a Wi-Fi to WWAN gateway.
Not all accessories fall neatly into these categories. Indeed, some accessories might fit into multiple categories, or transition between categories. Still, I’ve found these categories to be helpful when discussing various accessory integration challenges.
Do You Control the Firmware?
The key question here is Do you control the accessory’s firmware? If so, you have a bunch of extra options that will make your life easier. If not, you have to adapt to whatever the accessory’s current firmware does.
Simple Improvements
If you do control the firmware, I strongly encourage you to:
Support IPv6
Implement Bonjour [1]
These two things are quite easy to do — most embedded platforms support them directly, so it’s just a question of turning them on — and they will make your life significantly easier:
Link-local addresses are intrinsic to IPv6, and IPv6 is intrinsic to Apple platforms. If your accessory supports IPv6, you’ll always be able to communicate with it, regardless of how messed up the IPv4 configuration gets.
Similarly, if you support Bonjour, you’ll always be able to find your accessory on the network.
[1] Bonjour is an Apple term for three Internet standards:
RFC 3927 Dynamic Configuration of IPv4 Link-Local Addresses
RFC 6762 Multicast DNS
RFC 6763 DNS-Based Service Discovery
WAC
For a bound accessory, support Wireless Accessory Configuration (WAC). This is a relatively big ask — supporting WAC requires you to join the MFi Program — but it has some huge benefits:
You don’t need to write an app to configure your accessory. The user will be able to do it directly from Settings.
If you do write an app, you can use the EAWiFiUnconfiguredAccessoryBrowser class to simplify your configuration process.
HomeKit
For a bound accessory that works in the user’s home, consider supporting HomeKit. This yields the same onboarding benefits as WAC, and many other benefits as well. Also, you can get started with the HomeKit Open Source Accessory Development Kit (ADK).
Bluetooth LE
If your accessory supports Bluetooth LE, think about how you can use that to improve your app’s user experience. For an example of that, see SSID Scanning, below.
Claiming the Default Route, Or Not?
If your accessory publishes a Wi-Fi network, a key design decision is whether to stand up enough infrastructure for an iOS device to make it the default route.
IMPORTANT To learn more about how iOS makes the decision to switch the default route, see The iOS Wi-Fi Lifecycle and Network Interface Concepts.
This decision has significant implications. If the accessory’s network becomes the default route, most network connections from iOS will be routed to your accessory. If it doesn’t provide a path to the wider Internet, those connections will fail. That includes connections made by your own app.
Note It’s possible to get around this by forcing your network connections to run over WWAN. See Binding to an Interface in Network Interface Techniques and Running an HTTP Request over WWAN. Of course, this only works if the user has WWAN. It won’t help most iPad users, for example.
OTOH, if your accessory’s network doesn’t become the default route, you’ll see other issues. iOS will not auto-join such a network so, if the user locks their device, they’ll have to manually join the network again.
In my experience a lot of accessories choose to become the default route in situations where they shouldn’t. For example, a bound accessory is never going to be able to provide a path to the wider Internet so it probably shouldn’t become the default route. However, there are cases where it absolutely makes sense, the most obvious being that of a gateway accessory.
Acting as a Captive Network, or Not?
If your accessory becomes the default route you must then decide whether to act like a captive network or not.
IMPORTANT To learn more about how iOS determines whether a network is captive, see The iOS Wi-Fi Lifecycle.
For bound and stand-alone accessories, becoming a captive network is generally a bad idea. When the user joins your network, the captive network UI comes up and they have to successfully complete it to stay on the network. If they cancel out, iOS will leave the network. That makes it hard for the user to run your app while their iOS device is on your accessory’s network.
In contrast, it’s more reasonable for a gateway accessory to act as a captive network.
SSID Scanning
Many developers think that TN3111 iOS Wi-Fi API overview is lying when it says:
iOS does not have a general-purpose API for Wi-Fi scanning
It is not.
Many developers think that the Hotspot Helper API is a panacea that will fix all their Wi-Fi accessory integration issues, if only they could get the entitlement to use it.
It will not.
Note this comment in the official docs:
NEHotspotHelper is only useful for hotspot integration. There are both technical and business restrictions that prevent it from being used for other tasks, such as accessory integration or Wi-Fi based location.
Even if you had the entitlement you would run into these technical restrictions. The API was specifically designed to support hotspot navigation — in this context hotspots are “Wi-Fi networks where the user must interact with the network to gain access to the wider Internet” — and it does not give you access to on-demand real-time Wi-Fi scan results.
Many developers look at another developer’s app, see that it’s displaying real-time Wi-Fi scan results, and think there’s some special deal with Apple that’ll make that work.
There is not.
In reality, Wi-Fi accessory developers have come up with a variety of creative approaches for this, including:
If you have a bound accessory, you might add WAC support, which makes this whole issue go away.
In many cases, you can avoid the need for Wi-Fi scan results by adopting AccessorySetupKit.
You might build your accessory with a barcode containing the info required to join its network, and scan that from your app. This is the premise behind the Configuring a Wi-Fi Accessory to Join the User’s Network sample code.
You might configure all your accessories to have a common SSID prefix, and then take advantage of the prefix support in NEHotspotConfigurationManager. See Programmatically Joining a Network, below.
You might have your app talk to your accessory via some other means, like Bluetooth LE, and have the accessory scan for Wi-Fi networks and return the results.
Programmatically Joining a Network
Network Extension framework has an API, NEHotspotConfigurationManager, to programmatically join a network, either temporarily or as a known network that supports auto-join. For the details, see Wi-Fi Configuration.
One feature that’s particularly useful is it’s prefix support, allowing you to create a configuration that’ll join any network with a specific prefix. See the init(ssidPrefix:) initialiser for the details.
For examples of how to use this API, see:
Configuring a Wi-Fi Accessory to Join the User’s Network — It shows all the steps for one approach for getting a non-WAC bound accessory on to the user’s network.
NEHotspotConfiguration Sample — Use this to explore the API in general.
Secure Communication
Users expect all network communication to be done securely. For some ideas on how to set up a secure connection to an accessory, see TLS For Accessory Developers.
Revision History
2024-09-12 Improved the discussion of AccessorySetupKit.
2024-07-16 Added a preliminary discussion of AccessorySetupKit.
2023-10-11 Added the HomeKit section. Fixed the link in Secure Communication to point to TLS For Accessory Developers.
2023-07-23 First posted.
Hi Team,
I'm trying to capture inbound traffic for DNS responses and have experimented with the following rules, but they did not work.
NENetworkRule *dnsInboundTraffic = [[NENetworkRule alloc] initWithRemoteNetwork:nil remotePrefix:0 localNetwork:[NWHostEndpoint endpointWithHostname:@"0.0.0.0" port:@"53"] localPrefix:0 protocol:NENetworkRuleProtocolUDP direction:NETrafficDirectionInbound];
settings.includedNetworkRules = @[dnsInboundTraffic];
Could you please correct me if I'm making any mistakes while setting the rules?
How to commission a device to our fabric after adding it using Matter.Support
We have the following configuration:
eero border router
our own thermostat device that we are developing
no home pod or home TV are used
We have followed this guide
https://developer.apple.com/documentation/mattersupport/adding-matter-support-to-your-ecosystem
and implemented Matter Extension, as Matter.Framework is no more allowed to pair device.
In Matter Extension the following callbacks are fired:
override func selectThreadNetwork(from threadScanResults: [MatterAddDeviceExtensionRequestHandler.ThreadScanResult]) async throws -> MatterAddDeviceExtensionRequestHandler.ThreadNetworkAssociation
override func commissionDevice(in home: MatterAddDeviceRequest.Home?, onboardingPayload: String, commissioningID: UUID) async throws
In our demo app the following function completes without errors
try await request.perform()
The thermostat device seems to be successfully commissioned.
In https://developer.apple.com/documentation/mattersupport/adding-matter-support-to-your-ecosystem there is a comment that says:
Use Matter.Framework APIs to pair the accessory to your application with the provided onboardingPayload.
How should this thing be done ?
We tried to start the matter controller in the old way:
func start() -> Bool
{
if (self.matterController == nil)
{
let storage = MatterStorage.shared
let factory = MTRDeviceControllerFactory.sharedInstance()
let factoryParams = MTRDeviceControllerFactoryParams(storage: storage)
do
{
try factory.start(factoryParams)
}
catch
{
return false
}
let keys = FabricKeys()
let params = MTRDeviceControllerStartupParams(signing: keys, fabricId: UInt64(fabricId), ipk: keys.ipk)
params.vendorID = NSNumber(value: self.vendorId)
self.matterController = try? factory.createController(onExistingFabric: params)
let controllerNid = self.matterController?.controllerNodeID
if (self.matterController == nil)
{
self.matterController = try? factory.createController(onNewFabric: params)
}
}
return (self.matterController != nil)
}
Certificate are generated locally as in Matter Darwin example.
We tried to call
let params = MTRCommissioningParameters()
matterController?.commissionNode(withID: NSNumber(value: self.deviceNid), commissioningParams: params)
in commissionDevice of Matter Extension but we get error:
Invalid object state.
I would like to use NWProtocolQUIC in Swift's Network.framework to prepare multiple QUIC Streams and send different data to the server for each.
class QuicConnection {
var acceptConnection: NWConnection?
var openConnection: NWConnection?
var acceptConnectionState: NWConnection.State?
var openConnectionState: NWConnection.State?
var receiveFromAcceptConnection: String?
static func makeNWParameters() -> NWParameters {
let options = NWProtocolQUIC.Options(alpn: ["echo"])
options.direction = .bidirectional
let securityProtocolOptions: sec_protocol_options_t = options.securityProtocolOptions
sec_protocol_options_set_verify_block(securityProtocolOptions,
{ (_: sec_protocol_metadata_t,
_: sec_trust_t,
complete: @escaping sec_protocol_verify_complete_t) in
complete(true)
}, DispatchQueue.main)
return NWParameters(quic: options)
}
let group: NWConnectionGroup
init() {
print("init")
let parameters = Self.makeNWParameters()
let descriptor = NWMultiplexGroup(to: .hostPort(host: "192.168.0.20", port: 4242))
group = NWConnectionGroup(with: descriptor, using: parameters)
//subscribe()
group.stateUpdateHandler = { (state: NWConnectionGroup.State) in
print("state: \(state)")
switch state {
case .ready:
print("quic connected!")
default:
break
}
}
group.newConnectionHandler = { [weak self] (connection: NWConnection) in
print("new connection: \(connection)")
self?.acceptConnection = connection
self?.acceptConnection?.stateUpdateHandler = { [weak self] (state: NWConnection.State) in
self?.acceptConnectionState = state
}
self?.subscribeAcceptConnection()
self?.acceptConnection?.start(queue: DispatchQueue.main)
}
group.start(queue: DispatchQueue.main)
}
func createStream() {
//guard let group else { return }
let options = NWProtocolQUIC.Options()
options.direction = .bidirectional
let securityProtocolOptions: sec_protocol_options_t = options.securityProtocolOptions
sec_protocol_options_set_verify_block(securityProtocolOptions,
{ (_: sec_protocol_metadata_t,
_: sec_trust_t,
complete: @escaping sec_protocol_verify_complete_t) in
complete(true) // Insecure !!!
}, DispatchQueue.main)
openConnection = NWConnection(from: group)
openConnectionState = openConnection?.state
openConnection?.stateUpdateHandler = { [weak self] (state: NWConnection.State) in
self?.openConnectionState = state
print("state: \(state)")
switch state {
case .ready:
print("stream connected!")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self?.send(message: "marker1")
}
default:
break
}
}
openConnection?.start(queue: DispatchQueue.main)
}
func send(message: String) {
print("send start")
let completion: NWConnection.SendCompletion = .contentProcessed { (error: Error?) in
if let error = error {
print("send error: \(error)")
} else {
print("send successful")
}
}
openConnection?.send(content: message.data(using: .utf8)!,
contentContext: .defaultMessage,
isComplete: true,
completion: completion)
print("message: \(message)")
}
}
When the app starts, it calls the init function of this QuicConnection class to create an instance and build the QUIC tunnel." quic connected" log appears, and when a specific action is performed in the app, the createStream function is called to put up a stream." stream connected" log is displayed, but when I then try to send data using the send function, the "send successful" message is displayed, but there is no output on the server side indicating that the message was received from the client. However, when I try to send data using the send function after that, I get a "send successful" message.
I don't think there is a problem on the server side, because I can communicate well when only NWConnection is used without NQConnectionGroup. The server is using quic-go.
I would like to borrow knowledge from those who have handled QUIC streams in Swift.
Below are Apple's announcement and official documents that I referred to. I wrote the code referring to these, but even though I can connect the QUIC tunnels, I can not send data by setting up individual streams.
https://developer.apple.com/videos/play/wwdc2021/10094/
https://developer.apple.com/documentation/network/nwprotocolquic
Note The PF side of this is now covered by TN3165 Packet Filter is not API.
Network Extension (NE) providers let you create products for VPN, content filtering, transparent proxying, and so on. Various Apple platforms support various different provider types. See TN3134 Network Extension provider deployment for the details.
On iOS NE providers are the only game in town. It’s not possible to implement products like this in any other way. On macOS, however, there are a variety of other ad hoc techniques you might use. These include:
Packet Filter (PF) aka pfctl (see its man page)
A utun interface (see <net/if_utun.h>)
Network kernel extensions (NKE), aka KEXTs
People use these techniques for a variety of reasons. For example, you might have a product that predates the NE provider architecture, or you might want to reuse code that you wrote for another platform.
Regardless of the reason, be aware that DTS doesn’t support these ad hoc techniques. If you’re building a product like this for macOS, create an NE provider.
We’ve adopted this policy because, in our experience, these ad hoc techniques tend to be very brittle, and thus are not supportable in the long term. A great example of this is PF. There’s no documented arbitration scheme for PF rules so, as a third-party developer, the rules you install might be incompatible with the rules set up by various macOS features, other third-party developers, the user, or the site admin.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Revision History
2028-02-09 Added a link to TN3165.
2023-11-23 First posted.
I work on an app that operates a HW device that acts as a BLE peripheral. Our BLE code stack has not changed much since 2017 and has been working very well over the years. We recently started seeing a lot of customer complaints and bad App Store reviews that the device was not working.
I have been investigating this for several weeks now and I'm struggling to narrow down the cause, but it seems to be a change in iOS. With the same app and device FW the issue is almost exclusively seen on iOS 17.x even though ~40% of our user base is still on iOS 16.x.
From my investigation what I see is the CBPeripheral getting stuck in connecting state. When it is in this state advertisements are seen in our app, and other apps are able to connect to the device (nRF Connect for example). If I cancel the connection the CBPeripheral then gets stuck in the disconnecting state. I can only toggle between these two states and it will remain like this for days.
I have found that initializing a new CBCentralManger will sometimes "fix" the issue. However, about 50% of the time the new CBCentralManager comes up in the unknown state so CoreBluetooth as a whole seems to be in a weird state.
More effective is killing the app and relaunching. But even then sometimes the CBPeripheral immediately gets stuck again and it takes multiple killing/launching the app to get back in a working state.
Few points that seem relevant:
App has central and peripheral background modes enabled.
App uses state restoration, though most of the times I see this issue there was not a state restore that happened.
To reproduce the issue the app needs to be in the background for some amount of time, and it happens on foregrounding.
We will in some cases scan/connect in the background, but I have reproduced this issue without that.
Is anyone else seeing this issue or have ideas what might be causing it?
Hi,
I'm looking for feedback regarding SCNetworkReachability under macOS Sonoma.
It seems that since beta 3 the notifications behaviour changed.
In a LaunchAgent I'm using SCNetworkReachabilityCreateWithName + SCNetworkReachabilitySetCallback + SCNetworkReachabilityScheduleWithRunLoop and wait for callbacks looking at the kSCNetworkReachabilityFlagsReachable flag. This is running fine under macOS 12.x, 13.x and 14.0 for more than a year.
If I log all callback entries I observe unexpected notifications as if the looked host became unreachable for very small amount of time (ms). The host is flagged as unreachable then few ms later reachable again then unreachable again.
Fast switching is fine, I can accept that the service is unreachable even for 1s but the probleme is the latest status do not reflect actual reachability of the service.
This is in a corporate network with the complexity of using a proxy.pac.
Does anybody noticed something similar ?
I filled a Feedback FB13442134 in case it could be a regression of 14.2
The connection using MultipeerConnectivity between iPhones and iPads with iOS 17 or higher installed is not functioning. This issue was not observed on iOS 16 or earlier versions.
Currently, when advertising from an iPhone, the iPad can detect the device, but the event handling to accept invitations on the iPhone is not being triggered correctly. Consequently, not responding to invitations is preventing the connection.
While the Wi-Fi feature is enabled, previously, it was possible to establish connections without being connected to a specific Wi-Fi network. However, presently, connection seems to occur only when the iPad and iPhone are on the same network.
Moreover, irregular connections are occurring between iPhones, yet there is no connection whatsoever between iPads and iPhones.
I want to allow network access in my app but I have an error
nw_proxy_resolver_create_parsed_array [C1.1.1 proxy pac] Evaluation error: NSURLErrorDomain: -1003
which crashes my app although the seek command works and I get a correct value back from the internet server. I understood I could fix this as foilows?
There is a section Info. Within Xcode 15 where you can find Custom macOS Application Target Properties. I selected App Transport Security Settings and the after pressing the drop down menu selected Allow Arbitrary Loads. Then to the left of that I press the menu and it shows YES and NO but if I try to select either of them neither appears in the key value box? Also I thought this would create a new Info.plist which I could then add my key values- but nothing happens..
I am very new to the so any help is much apprecated