简单的Webview:navigationDelegate在启动时崩溃 [英] Simple Webview: navigationDelegate crashes on start
问题描述
我的WebView有一个小问题.这就是我在应用程序中所做的:
I have a small problem with my WebView. This is what I do in my app:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet var webView: WKWebView! // draged from storyboard
override func viewDidLoad() {
super.viewDidLoad()
var urlToLoad : (String)
urlToLoad = "http://wwww.myapp.com"
webView.sizeToFit()
webView.isUserInteractionEnabled = true
let url = URL(string: urlToLoad)
let request = URLRequest(url:url!)
//webView.navigationDelegate = self
webView.load(request)
}
如您所见,注释了"webView.navigationDelegate = self"行.如果我取消注释,我的应用程序将在启动时崩溃并告诉我:
As you see the row "webView.navigationDelegate = self" is commented. If I uncomment it my app will crash on start and telling me this:
调试器:libc ++ abi.dylib:终止于类型为NSException的未捕获异常
Debugger: libc++abi.dylib: terminating with uncaught exception of type NSException
关于为什么会发生这种情况以及如何解决这个问题的任何想法?我需要这样做,以便使用已经在页面中实现的"didFinish导航"之类的方法,但从未调用过它们.
Any idea of why is this happening and how to solve this? I need this in order to use methods like "didFinish navigation" that I already implemented in the page but they are never called.
还有,通过查看我的代码...,您看到我在使用Webview时应该进行的任何更改吗?
Also, by having a look at my code... you see anything I should change regarding the use of my webview?
感谢您对我的帮助.
推荐答案
您正在使用UIWebView,并尝试调用WKWebView的方法,由于UIWebView上发送的选择器无法识别,导致应用崩溃.
You are using UIWebView and trying to call the methods of WKWebView which is leading to crash your app due to unrecognised selector send on UIWebView.
尝试创建新项目并使用下面提到的代码.
Try to create new project and use below mentioned code.
将"WebKit"框架导入您的类.
import "WebKit" framework to your class.
override func viewDidLoad() {
super.viewDidLoad()
let myWebView:WKWebView = WKWebView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
myWebView.navigationDelegate = self;
let url = URL(string: "https://www.Apple.com")!
myWebView.load(URLRequest(url: url))
self.view.addSubview(myWebView)
}
然后实现WKNavigationDelegate方法
then implement WKNavigationDelegate method
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
let url = webView.url
print(url as Any) // this will print url address as option field
if url?.absoluteString.range(of: ".pdf") != nil {
pdfBackButton.isHidden = false
print("PDF contain")
}
else {
pdfBackButton.isHidden = true
print("No PDF Contain")
}
}
希望这对您有帮助!
这篇关于简单的Webview:navigationDelegate在启动时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!