Created
October 11, 2017 09:19
-
-
Save kraigspear/ee53b869f9c292f0d02c466a17f63e80 to your computer and use it in GitHub Desktop.
Connect to a WIFI hotspot programmatically in iOS 11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// NetworkTest | |
// | |
// Created by Kraig Spear on 10/10/17. | |
// Copyright © 2017 spearware. All rights reserved. | |
// | |
import UIKit | |
import NetworkExtension | |
final class ViewController: UIViewController { | |
private let SSID = "" | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
} | |
@IBAction func connectAction(_ sender: Any) { | |
let hotspotConfig = NEHotspotConfiguration(ssid: SSID, passphrase: "", isWEP: false) | |
NEHotspotConfigurationManager.shared.apply(hotspotConfig) {[unowned self] (error) in | |
if let error = error { | |
self.showError(error: error) | |
} | |
else { | |
self.showSuccess() | |
} | |
} | |
} | |
@IBAction func disconnectAction(_ sender: Any) { | |
NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: SSID) | |
} | |
private func showError(error: Error) { | |
let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) | |
let action = UIAlertAction(title: "Darn", style: .default, handler: nil) | |
alert.addAction(action) | |
present(alert, animated: true, completion: nil) | |
} | |
private func showSuccess() { | |
let alert = UIAlertController(title: "", message: "Connected", preferredStyle: .alert) | |
let action = UIAlertAction(title: "Cool", style: .default, handler: nil) | |
alert.addAction(action) | |
present(alert, animated: true, completion: nil) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know this is kinda old but I just wanted to add something so people that stumble upon this don't get confused in the future.
If the error is nil in the callback it does not mean you are connected. It means the configuration was added successfully.
From the documentation in
NetworkExtension/NEHotspotConfigurationManager.h
:The interesting part is
The NSError passed to this block will be nil if the configuration is successfully stored, non-nil otherwise
.The completionhandler gets called before the connection is actually established.
You have to check if the SSID changed to the expected one yourself afterwards.