问题描述
这是我对堆栈溢出的第一个问题,请耐心等待。
我正在使用WKWebView
制作一个单视图应用程序。只需使用url
即可加载Web应用
我在做什么和我想要什么,我已经在下面解释了一切
Xcode版本:11.7
iOS版本:13.7
这是Outlet
中的ViewController
。
@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()
}
}
如果可以访问Internet,则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的设置以启用Internet。 Output of Alert method
我想要什么
当用户从设置返回到应用时,应在AppDelegate
中调用loadMoma()
方法。
为此,我在类ViewController
中创建了AppDelegate
的实例,如下所示:-
var vc = ViewController()
我在loadMoma
中叫applicationWillEnterForeground
像这样:-
func applicationWillEnterForeground(_ application: UIApplication) {
print("applicationWillEnterForeground")
if !flag {
vc.loadMoma()
}
}
flag
与check
相同的地方。
但是事情是,当我在运行应用程序时按主页按钮或导航到设置时,甚至不会触发打印。
请告诉我应该将vc.loadMoma()
放在AppDelegate
中的位置,以获取上面介绍的功能。
谢谢
解决方法
当您使用iOS 13.7版和Xcode 11.7版时,应该使用Scene委托生命周期方法来满足您的要求。
每当用户从其他应用程序回到您的应用程序时,都会触发SceneDelegate的sceneWillEnterForeground和sceneDidBecomeActive方法。因此,您可以放置代码以进行Internet连接检查,并在sceneWillEnterForeground方法内调用loadMoma()方法。
#HappyCoding
,尝试在applicationDidBecomeActive中打开要在应用程序上执行的代码,并在退出时在AppDelegate的applicationDidEnterBackground中运行要运行的代码。