我目前正在尝试通过WebView在移动设备(iPhone和iPad)上部署响应式网站。
以下是有关该应用的一些详细信息:
源代码:
ViewController.swift
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
// edit the url the app should load here
private var domain = "https://example.com/"
@IBOutlet weak var webView: WKWebView!
override func loadView() {
//delegates the navigation of other urls while still inside the webview
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
webView.allowsLinkPreview = false
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// calls the website in a 'iframe' style
let url = URL(string: domain)
let request = URLRequest(url: url!)
webView.load(request)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping ((WKNavigationActionPolicy) -> Void)) {
// outputs are for debugging purpose
print("webView :\(webView)" + "\n")
print("decidePolicyForNavigationAction :\(navigationAction)" + "\n")
print("decisionHandler :\(decisionHandler)" + "\n")
switch navigationAction.navigationType {
case .linkActivated:
print("request : " + navigationAction.request.url!.absoluteString)
self.webView?.load(navigationAction.request)
return
default:
break
}
if let url = navigationAction.request.url {
print("url : " + url.absoluteString)
}
decisionHandler(.allow)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
AppDelegate.swift:
import UIKit
import WebKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
尝试打开外部和内部链接时遇到了麻烦;该应用程序将发出信号SIGABRT。
据我所知,这个错误通常发生在Outlet不匹配时,但我的项目只有一个Outlet(WebView / ViewController)。我尝试删除它并重新创建它无济于事。
如果问题是在从外部链接加载的页面和我的应用程序之间没有出口,我无法看到如何解决这个问题,因为我无法控制网站。
注意:当我将webView.allowsLinkPreview设置为true(在func loadView()中)时,应用程序会加载新页面但需要相当长的时间。此事件也不会第二次调用webView函数。
任何帮助将不胜感激。 谢谢。
修改即可。根据评论中的要求,这是调试器抛出的内容:
libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
此外,Thread 1 SIGABRT信号似乎在AppDelegate类中。
答案 0 :(得分:0)
有趣的错误消息应该是
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed to -[myAppName webView:decidePolicyForNavigationAction:decisionHandler:] was not called'
在webView(_ webView:, decidePolicyFor navigationAction:, decisionHandler:)
的某个特定情况下,您没有decisionHandler(someValue)
,这就是它崩溃的原因。
所以在
case .linkActivated:
print("request : " + navigationAction.request.url!.absoluteString)
self.webView?.load(navigationAction.request)
return
在返回之前,您需要decisionHandler(someValue)
。