>我使用以下代码来检查互联网连接:
class Reachability {
let networkReachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")
func checkForReachability() {
self.networkReachabilityManager?.listener = { status in
print("Network Status: (status)")
switch status {
case .notReachable:
print("no internet connection detected")
//Show error here (no internet connection)
case .reachable(_), .unknown:
print("internet connection availible")
}
}
self.networkReachabilityManager?.startListening()
}
}
当存在连接时,它会成功调用 .reachable 中的块。但是在连接缺失的情况下,什么都没有叫,为什么?
我这样称呼它(保留对类的引用,所以它没有发布(
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let reachabilityManager = Reachability()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
reachabilityManager.checkForReachability()
return true
}
创建用于检查连通性的通用类
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() -> Bool {
return NetworkReachabilityManager()!.isReachable
}
}
并在需要的地方调用函数
if !Connectivity.isConnectedToInternet() {
// show Alert
return
}
创建一个名为 Connectivity
的 swift 类。您可以使用Alamofire
中的类NetworkReachabilityManager
并根据需要配置isConnectedToInternet()
方法。我只检查设备是否已连接到互联网。
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
用法-
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
或者你可以简单地这样做——
if let err = error as? URLError, err.code == URLError.Code.notConnectedToInternet{
// No internet connection
}else{
// your other errors
}