Connecting to Wi-Fi programmatically in iOS with Swift

With a little bit of code, you can prompt the user to connect to Wi-Fi network of your choice.

Published: May 19, 2021
See books

While working on SwitchBuddy I found that you can actually programatically initiate connection to specific Wi-Fi network. Here is a short post on how to do it.

The first step is to add some capabilities to your project. These are "Hotspot Configuration" and "Network Extensions" for a good measure.

Create configuration

The actual Swift code involves two parts. First you need to create a NEHotspotConfiguration instance and then apply it. There are variety of inits, I guess the most common one is going to be this variant:

let wiFiConfig = NEHotspotConfiguration(ssid: "network_name", passphrase: "password123", isWEP: false)

You need to provide the SSID which identifies the Wi-Fi network, then password if needed and specify the isWEP parameter. The docs are actually pretty good there.

Connect to the Wi-Fi

Once you have the configuration instance, you can continue to final step. Actually connecting to the Wi-Fi. Or rather prompting user to connect. Because each time user has to confirm the connection via system dialog and there is no way around it.

This is as straightforward as passing the configuration to the NEHotspotConfigurationManager.shared.apply like this:

NEHotspotConfigurationManager.shared.apply(wiFiConfig) { error in
            if let error = error {
                print(error.localizedDescription)
            }
            else {
                // user confirmed
            }
        }

The completion handler will contain error if something went wrong. If user declines the dialog, the error will be NEHotspotConfigurationError.userDenied. It probably makes sense to handle this one differently and explain to the user that they need to connect to continue.

Note that this completion will be called after the dialog is either confirmed or declined. This means that at this point, the Wi-Fi is very likely not yet connected and it may take even a few seconds to connect.

At this point you ideally need to implement some mechanism to check if the Wi-Fi has been joined successfully.

Uses: Xcode 12 & Swift 5.3

Filip Němeček profile photo

WRITTEN BY

Filip Němeček @nemecek_f@iosdev.space

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀