Evg*_*ban 0 reachability ios swift alamofire
我使用以下代码来检查互联网连接:
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()
}
}
Run Code Online (Sandbox Code Playgroud)
当连接存在时,它成功调用.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
}
Run Code Online (Sandbox Code Playgroud)
创建用于检查连接的公共类
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() -> Bool {
return NetworkReachabilityManager()!.isReachable
}
}
Run Code Online (Sandbox Code Playgroud)
并在您需要的地方调用该功能
if !Connectivity.isConnectedToInternet() {
// show Alert
return
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1305 次 |
| 最近记录: |