在我的应用程序中,我正在检查移动数据是否关闭,是否会显示弹出窗口,例如检查您的数据连接。为此我写了这段代码
import Foundation
import SystemConfiguration
public class Reachability {
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
}
}
但通过此代码,它仅检查 wifi 是否已连接。但如果我尝试使用 3g 移动数据,它总是显示您的移动数据未连接。那么我该如何解决这个问题呢?
尝试像下面的代码:
创建可达性类的对象,例如,
var internetReachability = Reachability()
现在在 viewDidLoad() 中编写以下代码,
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil)
self.internetReachability = Reachability.reachabilityForInternetConnection()
self.internetReachability.startNotifier()
self.updateInterfaceWithReachability(self.internetReachability)
现在创建函数来检查 wifi 和数据包的可达性,
func updateInterfaceWithReachability(reachability: Reachability)
{
let netStatus : NetworkStatus = reachability.currentReachabilityStatus()
switch (netStatus.rawValue)
{
case NotReachable.rawValue:
print("offline")
break
case ReachableViaWWAN.rawValue:
print("online")
break
case ReachableViaWiFi.rawValue:
print("online")
break
default :
print("offline")
break
}
}
// Rechability update status
func reachabilityChanged(sender : NSNotification!)
{
let curReach : Reachability = sender.object as! Reachability
self.updateInterfaceWithReachability(curReach)
}
希望对你有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)