什么是最简单的方法来检查互联网连接?
我找到了这个代码示例,但在Xcode11Swift5中是最有效的方法吗?
我只需要在调用我的从互联网下载的函数之前,在按钮按下的情况下检查连接。所以在调用我的函数之前进行简单的检查就可以了。这种持续监控是最有效的吗?还是我应该直接在我的按钮按下下使用一些东西。
import Network
class ViewController: UIViewController {
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "InternetConnectionMonitor")
override func viewDidLoad() {
monitor.pathUpdateHandler = { pathUpdateHandler in
if pathUpdateHandler.status == .satisfied {
print("Internet connection is on.")
} else {
print("There's no internet connection.")
}
}
monitor.start(queue: queue)
}
}
我使用的是 ashleymills 的 Reachability 框架。https:/github.comashleymillsReachability.swift。
你只需要通过导入。import ReachabilitySwift
然后就在你的视图控制器里面,你可以做例如:。
let reachability = try! Reachability()
if reachability.isReachable {
print("Internet connection is on.")
}
请参阅ReadMe中的ReadMe,了解更多关于如何使用闭包的例子.要注意的是,这是一个外部框架,可能没有最新的Swift版本。
导入SystemConfiguration。
import SystemConfiguration
在viewController类之前添加这个类。
public class Reachability {
class func isConnected() -> Bool {
var noAddress = 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))
noAddress.sin_len = UInt8(MemoryLayout.size(ofValue: noAddress))
noAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &noAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {noSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, noSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
现在在viewDidLoad中检查连接。
if Reachability.isConnected(){
print("Internet Connection is ON")
} else {
print("Internet Connection OFF")
}