ios - 尝试使用 Alamofire 检查 iOS 设备上的互联网连接

标签 ios swift alamofire reachability

我使用以下代码检查互联网连接:

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/

相关文章:

ios - 区分iOS7上的屏幕锁定和主页按钮按下

ios - 子类和 Storyboard - nil IBOutlets

ios - 从 API 检索数据以在数组中使用它们时如何摆脱 'The API method must be called from the main thread' 问题? swift

ios - swift 4: UITableView setSelected 函数在 iPad 上点击两次

arrays - Alamofire - 将字符串数组作为参数传递

iOS AVAudioSession,如何访问AVAudioRecorder 电平表

ios - 在 Swift 中使用定时器

swift - Swift 中的 Realm 迁移

php - Alamofire 下载文件存在进度问题

ios - 无法将类型 '__NSArrayI' (0x10df73c08) 的值转换为 'NSDictionary' (0x10df74108)