我正在开发一个ios应用程序(Swift 5),我试图在应用程序离线时显示一个屏幕,然后在用户重新连接时关闭。
我希望OfflineViewController在用户离线时出现,如果用户已连接,则会出现用户最后一个屏幕。
当我断开网络连接时,OfflineViewController会出现,但当我重新连接到网络时,OfflineViewController不会消失。我尝试添加一个按钮来关闭,但也不起作用。
我在下面附上了我的代码,你知道我做错了什么吗?
场景代理
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
let reachability = try! Reachability()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
// Send to homepage if logged in, otherwise login screen.
let accessToken: String? = KeychainWrapper.standard.string(forKey: "accessToken")
// If access token exists, skip login page
if accessToken != nil {
if let windowScene = scene as? UIWindowScene {
self.window = UIWindow(windowScene: windowScene)
let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "homeTabController") as! TabBarController
self.window!.rootViewController = vc
}
}
reachability.whenUnreachable = { [self] _ in
print("Not reachable (Scene delegate)")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "OfflineViewController") as! OfflineViewController
vc.modalPresentationStyle = .fullScreen
guard let firstScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
return
}
guard let firstWindow = firstScene.windows.first else {
return
}
let rootVC = firstWindow.rootViewController
rootVC?.dismiss(animated: true, completion: nil)
rootVC!.present(vc, animated: true, completion: nil)
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
}
脱机视图控制器
import UIKit
class OfflineViewController: UIViewController {
let reachability = try! Reachability()
override func viewDidLoad() {
super.viewDidLoad()
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
@IBAction func hitRefresh(_ sender: Any) {
reachability.whenReachable = { reachability in
self.dismiss(animated: true, completion: nil)
}
}
}
1条答案
按热度按时间wribegjk1#
我将开始从
OfflineViewController
中删除所有可达性代码。要删除的逻辑与要呈现的逻辑是一致的。然后使用
whenReachable
块更新场景代理中的可达性代码,该块消除当前的OfflineViewController
。你也应该避免在场景代理代码中使用
UIApplication.shared.connectedScenes
。你已经知道了场景。没有必要去找它。更新后的
whenUnreachable
:添加的
whenReachable
: