接受的答案是不工作在iOS上10。我找到了一個解決方法,並在AppDelegate中設置了一個定時器,它每隔5秒檢查currentRadioAccessTechnology屬性。因此,我們還需要一個功能來檢查WIFI連接是否可用,而不是無線電接入技術。
檢查WIFI連接可用:
class func isConnectedToWlan() -> 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(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
//Only Working for WIFI
let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
return isReachable && !needsConnection
}
設置計時器是這樣的:
Timer.scheduledTimer(timeInterval: TimeInterval.seconds(5.0), target: self, selector:
#selector(showNetworkMessage), userInfo: nil, repeats: true)
選擇被稱爲每5秒:
guard !Reachability.isConnecteToWlan() else {
//Connected to WLAN
return
}
guard let currentRadioAccessTechnology = info.currentRadioAccessTechnology else {
// No internet connection
return
}
guard (currentRadioAccessTechnology == CTRadioAccessTechnologyGPRS
|| currentRadioAccessTechnology == CTRadioAccessTechnologyEdge) else {
// 3G, LTE fast radio access Technology
return
}
if lastRadioAccessTechnology != nil {
guard let lastRadioAccessTechnology = lastRadioAccessTechnology,
(lastInfo != currentRadioAccessTechnology ||
lastInfo != currentRadioAccessTechnology) else {
//Internet connection did not change
return
}
}
// Internet connection changed to Edge or GPRS
// Store lastRadioAccessTechnology to check if internet connection changed
lastRadioAccessTechnology = currentRadioAccessTechnology
正確的+1推薦解決方案 –
幹得好!使用iOS7是最好的方法。 – elp
不要忘記在文件的頂部放置#import。 –