试图将WKWebview附加到UIApplication.shared.keywindow视图层次结构。当应用程序进入后台时,API会永远运行。但是当再次打开应用程序时,我遇到了这个问题:
[错误]无法加载资源:操作无法完成。软件导致连接中止
'var gOffscreenView:UIView? =零
func retainWKWebViewOffscreen(webView: WKWebView) {
if (gOffscreenView == nil) {
gOffscreenView = constructOffscreenView()
}
gOffscreenView?.addSubview(self.webView)
}
func cleanUpOffscreenView() {
if (gOffscreenView?.subviews.count == 0) {
gOffscreenView?.removeFromSuperview()
gOffscreenView = nil
}
}
func constructOffscreenView() -> UIView {
let view = UIView(frame: CGRect.zero)
view.clipsToBounds = true
let appWindow = UIApplication.shared.keyWindow
appWindow?.addSubview(view)
return view
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == self.kMoPubFrameKeyPathString) {
self.webView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
} else {
self.webView.frame = self.view.frame
}
}
@objc func keepWebViewRunning(_ notification: NSNotification) {
self.webView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
self.retainWKWebViewOffscreen(webView: self.webView)
}
@objc func remove(_ notification: NSNotification) {
self.webView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
self.view.backgroundColor = UIColor.yellow
self.view.addSubview(webView)
}`
我点击了此链接https://github.com/mopub/mopub-ios-sdk/blob/master/MoPubSDK/Internal/HTML/MPWebView.m
我还尝试设置计时器以调用虚拟javascript函数,以保持wkwebview不会进入空闲模式,但存在相同的问题。