配景:
iOS11后苹果提供 NEHotspotConfigurationManager 类直连周边Wi-Fi,iOS11前只能跳转到体系设置界面手动毗连Wi-Fi 。
- Xcode - General - Libraries - 引入NetworkExtension
- 前往Signing & Capabilities 添加Capability
/// 通过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 }}留意事项:
- 每次哀求主动毗连时,都会有体系弹框哀求用户授权。
- 在主动毗连网络后,大概存在网络无法立即哀求通的情况, 可以用轮询方式监听。
|