简单的 Web 视图: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")
}
}
希望对你有帮助!
这篇关于简单的 Web 视图:navigationDelegate 在启动时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!