1.获取WiFi名称的代码:
private func getWiFiName() -> String? {
guard let unwrappedCFArrayInterfaces = CNCopySupportedInterfaces() else {
// print("this must be a simulator, no interfaces found")
return nil
}
guard let swiftInterfaces = (unwrappedCFArrayInterfaces as NSArray) as? [String] else {
// print("System error: did not come back as array of Strings")
return nil
}
var wifiName: String?
for interface in swiftInterfaces {
print("Looking up SSID info for \(interface)") // en0
guard let unwrappedCFDictionaryForInterface = CNCopyCurrentNetworkInfo(interface as CFString) else {
// print("System error: \(interface) has no information")
return nil
}
guard let SSIDDict = (unwrappedCFDictionaryForInterface as NSDictionary) as? [String: AnyObject] else {
// print("System error: interface information is not a string-keyed dictionary")
return nil
}
wifiName = (SSIDDict["SSID"] as? String)
}
return wifiName
}
2.在iOS12和iOS13以后的版本上述代码返回为nil:
原因是iOS12以后的版本,需要额外设置权限信息,官网链接。
iOS13以后的版本,需要添加位置定位信息,用户同意使用后,才能获取wifi名称。
3.设置权限步骤:
3.1创建一个设置文件:
文件代码内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:demoapi.anniekids.net</string>
</array>
<key>com.apple.developer.networking.wifi-info</key>
<true/>
</dict>
</plist>
image.png
3.2在Xcode中设置加载上面创建文件:
过程:Xcode->targent->Build Settings->Code Signing Entitlements->$(SRCROOT)/上述文件路径。
例如我的路径:$(SRCROOT)/项目名称/Classes/AppDelegate/文件名称.plist。
image.png
4.设置定位权限
4.1info.plist设置用户权限弹窗提示字符串
9765503F-AF7B-4E73-84A3-346DF808F789.png4.2代码
/// 定位权限
static func checkLocation(isAlways: Bool, compelete: PermissionToolAuthorizeStatusCompelete?) {
let status = self.getLocationStatus()
if self.instence.locationManager == nil {
self.instence.locationManager = CLLocationManager.init()
self.instence.locationManager?.delegate = self.instence
}
switch status {
case .none: do {
self.instence.authorizeCompelete = compelete
if isAlways {
self.instence.locationManager?.requestAlwaysAuthorization()
}
else {
self.instence.locationManager?.requestWhenInUseAuthorization()
}
}
case .whenInUse: do {
if isAlways {
self.instence.authorizeCompelete = compelete
self.instence.locationManager?.requestAlwaysAuthorization()
}
else {
compelete?(.authorized)
}
}
case .always:
compelete?(.authorized)
case .denied:
compelete?(.denied)
}
}
网友评论