如何通知用户没有与swift 3的网络连接。我已经尝试了一堆解决方案,但到目前为止还没有一个解决方案。我不是在寻找网络连接的速度
答案 0 :(得分:4)
有很多资源显示如何检查Internet连接。例如,来自this。
func isInternetAvailable() -> Bool
{
var zeroAddress = sockaddr_in()
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()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
func showAlert() {
if !isInternetAvailable() {
let alert = UIAlertController(title: "Warning", message: "The Internet is not available", preferredStyle: .alert)
let action = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
您需要导入:
import Foundation
import SystemConfiguration