我使用以下代码检查互联网连接:
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中的block。但是在连接缺失的情况下没有任何调用,为什么?
我这样调用它(保持对类的引用,所以它没有被释放)
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
}
关于ios - 尝试使用 Alamofire 检查 iOS 设备上的互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49732620/