我对此感到非常沮丧,希望遇到类似问题的人可以提供帮助。当前项目使用Swift 2,iOS9和XCode 7.2。我有ViewConroller并尝试添加UIWebView或WKWebview作为子视图,但是,UIWebView崩溃了应用程序,而我的WKWebview没有加载URL,并且没有WKNavigationDelegate方法被调用。
``
import UIKit
import WebKit
class TestViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var placeholderView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, placeholderView.bounds.width, placeholderView.bounds.height))
webV.loadRequest(NSURLRequest(URL: NSURL(string: "https://www.google.com")))
webV.delegate = self;
self.view.addSubview(webV)
}
}
``
``
import UIKit
import WebKit
class TestViewController: UIViewController, WKNavigationDelegate {
@IBOutlet weak var placeholderView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let preferences = WKPreferences()
preferences.javaScriptEnabled = false
let webcon = WKWebViewConfiguration()
webcon.preferences = preferences
let webView: WKWebView = WKWebView(frame: CGRectMake(0, 0, placeholderView.bounds.width, placeholderView.bounds.height), configuration: webcon)
webView.navigationDelegate = self
let url = NSURL(string: "https://www.google.com")!
placeholderView.addSubview(webView)
placeholderView.bringSubviewToFront(webView)
webView.loadRequest(NSURLRequest(URL: url))
}
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
NSLog("Webview started Loading")
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
NSLog("%@", navigationAction.request.URL!)
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
print("\nWebview did finish load \(webView.request)", terminator: "")
}
}
``
我已经将WebKit导入框架工作,添加的应用程序允许任意加载到我的info.plist。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
答案 0 :(得分:1)
UIWebView
崩溃的原因几乎可以肯定,因为delegate
设置为不存在的对象。
我猜测WKWebView
委托方法没有被调用,因为你还没有设置navigationDelegate
属性(或者你做了,但你设置的对象是被解除分配。)
答案 1 :(得分:1)
嗯,只是尝试更改你的webView声明..先在var webView: WKWebView
(不要使用let
)的班级中声明你的webView,然后将self.webView = WKWebView(frame: CGRectMake(0, 0, placeholderView.bounds.width, placeholderView.bounds.height), configuration: webcon)
放入viewDidLoad中()