【发布时间】:2023-03-26 03:03:01
【问题描述】:
这是我关于堆栈溢出的第一个问题,请耐心等待。
我正在使用WKWebView 制作单视图应用程序。它只是使用url 加载网络应用程序
我在做什么和我想要什么,我在下面解释了所有内容
Xcode 版本:11.7 iOS 版本:13.7
这是ViewController 中的Outlet。
@IBOutlet var webView: WKWebView!
这个webView 通过调用viewDidLoad() 中的以下函数来获取负载。
func loadMoma() {
if let safeUrl = URL(string: url) {
let request = URLRequest(url: safeUrl)
webView.load(request)
}
}
这是我的viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
check = ConnectivityCheck.Connection()
if check {
loadMoma()
}
}
这里ConnectivityCheck.Connection()如果可以访问互联网则返回true,否则返回false。
使用此检查 loadMoma() 被调用。
如果没有连接,则不会发生任何事情,并且在 viewDidAppear() 方法中,Alert 函数会被调用,这是此代码。
override func viewDidAppear(_ animated: Bool) {
if !check {
self.Alert(Message: "Connection error!, please enable the Internet.")
}
}
Alert()方法的定义:-
func Alert (Message: String){
let alert = UIAlertController(title: "No Connectivity.", message: Message, preferredStyle: .alert)
let action = UIAlertAction(title: "Go to settings", style: .default) { (action) in
if let settingsUrl = URL.init(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.openURL(settingsUrl)
}
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
这会导致警报和一个按钮导航到 iPhone 的设置以启用互联网。 Output of Alert method
我想要什么
当用户从设置返回到应用程序时,应在AppDelegate 中调用loadMoma() 方法。
为此,我在 AppDelegate 类中创建了一个 ViewController 的实例,如下所示:-
var vc = ViewController()
我像这样在applicationWillEnterForeground 中调用了loadMoma:-
func applicationWillEnterForeground(_ application: UIApplication) {
print("applicationWillEnterForeground")
if !flag {
vc.loadMoma()
}
}
其中flag 与check 相同。
但是,当我在运行应用程序时按下主页按钮或导航到设置时,甚至打印都没有被触发。
请让我知道我应该将vc.loadMoma() 放在AppDelegate 的哪个位置以获得我上面描述的功能。
提前致谢
【问题讨论】:
-
applicationWillEnterForeground 会在应用处于前台状态时触发。从窗口对象中获取当前的根视图控制器。像这样。守卫让 yourvc = self.window?.rootViewController 作为? YourVC else { return } 做你的重新加载工作。
标签: ios swift iphone swift3 appdelegate