背景:
iOS11后苹果提供 NEHotspotConfigurationManager 类直连周边Wi-Fi,iOS11前只能跳转到系统设置界面手动连接Wi-Fi 。
- 前往开发者中心给AppID配置连接WIFI权限
-
Xcode - General - Libraries - 引入NetworkExtension
-
前往Signing & Capabilities 添加Capability
- Code 代码
/// 通过WiFi名称和密码连接到指定WiFi
/// - Parameters:
/// - ssid: WiFi SSID
/// - pwd: WiFi密码
/// - isWEP: 是否是WEP模式
/// - complete: 连接成功返回Yes, 失败返回False
public static func connectWithSSIDAndPwd(
ssid: String,
pwd: String,
isWEP: Bool = false,
complete: ((Bool, NEHotspotConfigurationError?) -> Void)?) {
let config = NEHotspotConfiguration.init(ssid: ssid, passphrase: pwd, isWEP: isWEP)
NEHotspotConfigurationManager.shared.apply(config) { (error) in
var isSuccess = false
if error == nil {
let currentSSID = getWiFiSSID()
if currentSSID == ssid {
isSuccess = true
} else {
isSuccess = false
}
} else {
isSuccess = false
XCGLog.info(error as Any)
}
//存在已经连接的情况,error code = 13 优先考虑isSuccess
if isSuccess {
complete?(isSuccess, nil)
} else {
// 将连接wifi api返回的error 转化为 NEHotspotConfigurationError 类型
let errorCode = error != nil ? NEHotspotConfigurationError.init(
rawValue: ((error as NSError?)?.code)!
) : nil
if errorCode == .alreadyAssociated {
isSuccess = true
}
complete?(isSuccess, errorCode)
}
}
}
/// 获取iPhone当前连接的WiFi SSID
/// - Returns: SSID
public static func getWiFiSSID() -> String? {
if #available(iOS 13.0, *) {
//系统版本高于13.0 未开启地理位置权限 需要提示一下
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined {
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
}
}
if let interfaces = CNCopySupportedInterfaces(),
let interfacesArray = CFBridgingRetain(interfaces) as? [AnyObject],
interfacesArray.isEmpty == false {
let interfaceName: CFString = interfacesArray[0] as! CFString
let ussafeInterfaceData = CNCopyCurrentNetworkInfo(interfaceName)
let interfaceData = ussafeInterfaceData as? [String: Any]
let ssid = interfaceData?["SSID"] as? String
XCGLog.info("Get SSID is: \(ssid ?? "nil")")
return ssid
}
return nil
}
}
注意事项:
- 每次请求自动连接时,都会有系统弹框请求用户授权。
- 在自动连接网络后,可能存在网络无法立即请求通的情况, 可以用轮询方式监听。