如何在 Swift 3 或 Swift 4 中检查互联网连接? [复制]
Posted
技术标签:
【中文标题】如何在 Swift 3 或 Swift 4 中检查互联网连接? [复制]【英文标题】:How to check internet connection in Swift 3 or Swift 4? [duplicate] 【发布时间】:2016-11-11 04:31:52 【问题描述】:我尝试在 Swift 3 中检查互联网连接,但代码对我不起作用。
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(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress)
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: UInt32(0))
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0
return false
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
我还导入了 SystemConfiguration 框架。请建议如何检查。
【问题讨论】:
定义“不工作”。 您可以查看此链接以供参考。它包含连接或断开连接时的网络检查。 ***.com/questions/40066530/… 【参考方案1】:最新的 swift3 代码
这里 检查互联网连接的最简单方法是使用 ios 可达性 API。检查此波纹管链接并下载将可达性文件添加到您的项目。您必须并且应该将系统配置框架添加到项目中
[1]: https://github.com/ashleymills/Reachability.swift/tree/feature/ios10
完成上述工作后,只需编写此代码来检查网络连接。这里我也写了一些警告消息。
func networkStatusChanged(_ notification: Notification)
let userInfo = (notification as NSNotification).userInfo
print(userInfo!)
func interNetChecking( )
let status = Reach().connectionStatus()
switch status
case .unknown, .offline:
let alert = UIAlertController(title: "Check", message: "Internet Connection is Required at first time running the app to load images and videos ", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
DispatchQueue.main.async(execute:
self.present(alert, animated: true, completion: nil)
)
print("Not connected")
case .online(.wwan):
print("Connected via WWAN")
case .online(.wiFi):
print("Connected via WiFi")
【讨论】:
【参考方案2】: func isConnectedToNetwork() -> Bool
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress)
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags)
return false
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
problemstucks.com
【讨论】:
如果您连接到 wi-fi 但无法连接到互联网(打开谷歌页面),它仍然返回 true 表示可达。错了。【参考方案3】:在 Alamofire 的情况下
import Alamofire
// 像这样添加到您的 viewDidLoad() 或 AppDelegate 中
let reachabilityManager = NetworkReachabilityManager()
reachabilityManager.listener = status in
switch status
case .notReachable:
print("The network is not reachable")
self.onInternetDisconnection()
case .unknown :
print("It is unknown whether the network is reachable")
self.onInternetDisconnection() // not sure what to do for this case
case .reachable(.ethernetOrWiFi):
print("The network is reachable over the WiFi connection")
self.onInternetConnection()
case .reachable(.wwan):
print("The network is reachable over the WWAN connection")
self.onInternetConnection()
【讨论】:
别忘了给reachabilityManager.startListening()
打电话,否则听者根本不会被调用。这是一个有趣的链接,因为在使用此代码的模拟器上需要考虑一些事情:github.com/Alamofire/Alamofire/issues/2275以上是关于如何在 Swift 3 或 Swift 4 中检查互联网连接? [复制]的主要内容,如果未能解决你的问题,请参考以下文章