我想检查wifi是否已关闭,然后向用户显示警告以检查他/她的连接性。
我找到这样的代码,但它会检查是否有互联网连接,而不是检查wifi是打开还是关闭:
func isConnectionAvailble()->Bool{
var rechability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.apple.com").takeRetainedValue()
var flags : SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(rechability, &flags) == 0
{
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
答案 0 :(得分:5)
你不能
使用Apple's reachability类,您可以根据NetworkStatus
结构区分三件事:
typedef enum : NSInteger {
NotReachable = 0, // 1
ReachableViaWiFi, // 2
ReachableViaWWAN // 3
} NetworkStatus;
您无法检查WiFi是否已关闭,或WiFi是否已开启但附近没有WiFi网络,或者是否已打开飞行模式。
对于移动数据,您可以使用电话类查找您的设备是否能够进行移动数据连接(iPhone而不是iPad,以及插入的SIM卡),并且您可以检测移动数据是否在首选项中被禁用你的申请。
答案 1 :(得分:3)
找到以下内容,这对我很有帮助(在Apple Developer Forums上找到)。以下代码适用于Swift 4。
<resources>
<!-- the theme applied to the application or activity -->
<style name="AppTheme"
parent="Theme.AppCompat.Light">
<item name="actionBarStyle">@style/MyActionBarStyle</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<!-- ActionBar styles -->
<style name="MyActionBarStyle"
parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="background">@drawable/action_bar</item>
</style>
</resources>
然后,您可以通过以下方式检查设备是否已连接到Wi-Fi:
func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces:CFArray = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces){
let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, to: AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)" as CFString)
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
for dictData in interfaceData! {
if dictData.key as! String == "SSID" {
currentSSID = dictData.value as! String
}
}
}
}
}
return currentSSID
}
不完美,但如果设备未连接到Wi-Fi网络,您可以要求用户连接到Wi-Fi网络:
if fetchSSIDInfo() != nil {
/* Wi-Fi is Connected */
}
答案 2 :(得分:2)
经过swift 4
和swift 5
let nwPathMonitor = NWPathMonitor()
nwPathMonitor.pathUpdateHandler = { path in
if path.usesInterfaceType(.wifi) {
print("Path is Wi-Fi")
} else if path.usesInterfaceType(.cellular) {
print("Path is Cellular")
} else if path.usesInterfaceType(.wiredEthernet) {
print("Path is Wired Ethernet")
} else if path.usesInterfaceType(.loopback) {
print("Path is Loopback")
} else if path.usesInterfaceType(.other) {
print("Path is other")
}
}
nwPathMonitor.start(queue: .main)
答案 3 :(得分:1)
您可以查看官方Apple样本的Reachability: https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html
var netStatus = reachability.currentReachabilityStatus()
var connectionRequired = reachability.connectionRequired()
var statusString = ""
switch netStatus {
case NotReachable:
break
case ReachableViaWWAN:
//DATA
break
case ReachableViaWiFi:
//WIFI
break
}
答案 4 :(得分:1)
正如@abba_de_bo已经提到的那样:你可以获取当前的SSID并检查它是否设置或为零。
这是Apple answer爱斯基摩人给出的这个问题:
使用Swift基于CF的API的技巧是尽快将数据放入“Swift空间”。
func currentSSIDs() -> [String] {
guard let interfaceNames = CNCopySupportedInterfaces() as? [String] else {
return []
}
return interfaceNames.flatMap { name in
guard let info = CNCopyCurrentNetworkInfo(name as CFString) as? [String:AnyObject] else {
return nil
}
guard let ssid = info[kCNNetworkInfoKeySSID as String] as? String else {
return nil
}
return ssid
}
}
请注意,这会返回一个名称数组;你如何处理非标准案例(没有元素,多个元素)取决于你。
确保import SystemConfiguration.CaptiveNetwork
。否则,构建将失败并显示以下错误消息:
答案 5 :(得分:-1)
您可以使用此方法检查:
首先导入此框架:
import SystemConfiguration.CaptiveNetwork
func isWifiEnabled() -> Bool {
var hasWiFiNetwork: Bool = false
let interfaces: NSArray = CFBridgingRetain(CNCopySupportedInterfaces()) as! NSArray
for interface in interfaces {
// let networkInfo = (CFBridgingRetain(CNCopyCurrentNetworkInfo(((interface) as! CFString))) as! NSDictionary)
let networkInfo: [AnyHashable: Any]? = CFBridgingRetain(CNCopyCurrentNetworkInfo(((interface) as! CFString))) as? [AnyHashable : Any]
if (networkInfo != nil) {
hasWiFiNetwork = true
break
}
}
return hasWiFiNetwork;
}