我在该项目中的一个Demo项目中创建了可达性我有两个视图控制器,如果有互联网连接我正在显示OnlineViewController如果没有互联网连接我正在显示OfflineViewController。请参阅我在Appdelegate.swift中实现的以下代码。
var reachability:Reachability?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityStatusChanged(_:)), name: .reachabilityChanged, object: nil)
reachability = Reachability.forInternetConnection()
reachability!.startNotifier()
return true
}
我的功能就像这个
@objc func reachabilityStatusChanged(_ sender: NSNotification) {
var remoteHostStatus = self.reachability!.currentReachabilityStatus()
if (remoteHostStatus == NotReachable)
{
print ("no net")
let testController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OfflineViewController") as! OfflineViewController
window!.rootViewController = testController
window!.makeKeyAndVisible()
}
else
{
let testController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OnlineViewController") as! OnlineViewController
window!.rootViewController = testController
window!.makeKeyAndVisible()
print (" wifi")
}
}
现在我的问题是我想在该项目的实时项目中实现相同的功能,我有3个故事板和多个视图控制器。那么如果有互联网连接,如何再次显示用户当前屏幕。
答案 0 :(得分:1)
我用以下代码解决了我的问题。我不确定我的答案是对还是错。
@objc func reachabilityStatusChanged(_ sender: NSNotification) {
var remoteHostStatus = self.reachability!.currentReachabilityStatus()
if (remoteHostStatus == NotReachable)
{
print ("no net")
let testController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OfflineViewController") as! OfflineViewController
window!.rootViewController = testController
window!.makeKeyAndVisible()
}
else
{
UserTypeValidateCall()
}
}.
//MARK:- Validating User Type
func UserTypeValidateCall()
{
let Usertype = UserDefaults.standard.string(forKey: "Usertype")
print("Usertype-----",Usertype)
if(( Usertype) != nil)
{
if (Usertype?.isEqual("Parent"))!
{
ParentDashBoardEnter()
}
else if (Usertype?.isEqual("Employee"))!
{
TeacherDashBoardEnter()
}
else if (Usertype?.isEqual("Admin"))!
{
AdminDashBoardEnter()
}
}
else
{
LoginScreenEnter()
}
}
答案 1 :(得分:0)
同样在项目中使用此函数并将用户导航到特定的视图控制器。
有关详细信息,请参阅此链接。 Check for internet connection with Swift
答案 2 :(得分:0)
import UIKit
import Reachability
class CommonUtility: NSObject {
class func isConnected() -> Bool{
let reachability:Reachability = Reachability.forInternetConnection()
let networkStatus = reachability.currentReachabilityStatus().rawValue
return networkStatus != 0
}
}
答案 3 :(得分:0)
//使用以下链接下载它,只需将Reachability Folder拖放到您的项目
即可https://github.com/ashleymills/Reachability.swift
或
pod'ReachabilitySwift','〜> 4.1'
注意:这里的ReachabilitySwift版本是基于你必须要的swift版本
let reachability = Reachability()!
override func viewDidLoad()
{
super.viewDidLoad()
}
if (reachability.isReachable)
{
// your code
}
else
{
// your code
}