Câu trả lời được chấp nhận không hoạt động trên iOS 10.Tôi tìm thấy một workaround và thiết lập một bộ đếm thời gian trong AppDelegate đó là kiểm tra tài sản hiện tạiRadioAccessTechnology mỗi 5 giây. Vì vậy, chúng tôi cũng cần một chức năng để kiểm tra xem kết nối WIFI có sẵn thay cho công nghệ truy cập vô tuyến hay không.
Kiểm tra nếu WIFI kết nối có sẵn:
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
}
Cài đặt bộ đếm thời gian như thế này:
Timer.scheduledTimer(timeInterval: TimeInterval.seconds(5.0), target: self, selector:
#selector(showNetworkMessage), userInfo: nil, repeats: true)
Selector được gọi là mỗi 5 giây:
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 cho đúng, giải pháp được đề nghị –
Thực hiện tốt Ben! Với iOS7 là cách tốt nhất. – elp
Đừng quên đặt #import ở đầu tệp của bạn. –