我一直在尝试检查互联网连接。如果设备连接到互联网,那么它将转到MainStoryboard上的初始viewController,否则它会在同一个故事板上显示另一个viewController。但是这段代码对我不起作用。我没有收到任何错误,它只是不起作用。
这是截图: Screenshot
以下是我在AppDelegate.swift中写的内容:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var reachability: Reachability?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = .lightContent
NotificationCenter.default.addObserver(self, selector: #selector(ReachabilityCheck(_:)), name: NSNotification.Name.reachabilityChanged, object: nil)
return true
}
功能是:
@objc func ReachabilityCheck(_: Notification) {
var remoteHostStatus = self.reachability!.currentReachabilityStatus()
if remoteHostStatus == NotReachable
{
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let offlineViewController = mainStoryboard.instantiateViewController(withIdentifier: "notReachable") as! notReachableViewController
window!.rootViewController = offlineViewController
window!.makeKeyAndVisible()
}else
{
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = mainStoryboard.instantiateViewController(withIdentifier: "mainNav") as! UINavigationController
window!.rootViewController = initialViewController
window!.makeKeyAndVisible()
}
}
我该怎么做才能让它发挥作用?请帮忙!
答案 0 :(得分:0)
雨燕4
创建一个新的Swift类
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
//用法.....
if Connectivity.isConnectedToInternet() == true {
print("Yes! internet is available.")
// do some tasks..
}
else
{
// self.view.makeToast("Yes! internet is available.")
print("Yes! internet is available.")
}