如何在 swift 2.2 中检查 3G、4G 和 wifi 互联网连接 [英] How to check 3G,4G and wifi internet connection in swift 2.2
本文介绍了如何在 swift 2.2 中检查 3G、4G 和 wifi 互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
导入基础导入系统配置
公共类可达性{
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
}
我正在使用上面编写的代码来检查我的应用程序的互联网连接,这仅检查 3G 和 WIFI 连接.但我还需要检查 4G 连接.谁能帮我找到解决方案.
I am using the above written code for checking internet connection for my app, this checks only 3G and WIFI connections. But I need to check for 4G Connections also. Can anyone help me to find the solution.
推荐答案
这里是 Reachability 来自 Apple,您需要下载 Reachability.h/.m 并将其拖到您的项目中.
Here is the Reachability from Apple, you need to download and drag Reachability.h/.m to your project.
然后导入 CoreTelephony
并尝试以下操作.
Then import CoreTelephony
and try below.
if let reachability = Reachability.forInternetConnection() {
reachability.startNotifier()
let status = reachability.currentReachabilityStatus()
if status == .init(0) {
// .NotReachable
print("Not Reachable")
}
else if status == .init(1) {
// .ReachableViaWiFi
print("Reachable Via WiFi")
}
else if status == .init(2) {
// .ReachableViaWWAN
let netInfo = CTTelephonyNetworkInfo()
if let cRAT = netInfo.currentRadioAccessTechnology {
switch cRAT {
case CTRadioAccessTechnologyGPRS,
CTRadioAccessTechnologyEdge,
CTRadioAccessTechnologyCDMA1x:
print("Reachable Via 2G")
case CTRadioAccessTechnologyWCDMA,
CTRadioAccessTechnologyHSDPA,
CTRadioAccessTechnologyHSUPA,
CTRadioAccessTechnologyCDMAEVDORev0,
CTRadioAccessTechnologyCDMAEVDORevA,
CTRadioAccessTechnologyCDMAEVDORevB,
CTRadioAccessTechnologyeHRPD:
print("Reachable Via 3G")
case CTRadioAccessTechnologyLTE:
print("Reachable Via 4G")
default:
fatalError("error")
}
}
}
}
这篇关于如何在 swift 2.2 中检查 3G、4G 和 wifi 互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文