使用以下代码进行快速操作:
super.viewDidLoad()
let webView = UIWebView(frame: self.view.bounds)
view.addSubview(webView)
let URL = NSURL(string: "http://www.google.com")
webView.loadRequest(NSURLRequest(URL: URL!))
println(webView.loading)它打印错误,屏幕是空白的。这是怎么解决的?
发布于 2015-03-29 23:50:42
这是完全正常的行为。在UI事件(在本例中为UIWebView )完成执行之前,viewDidLoad实际上不会开始加载内容。因此,检查它会立即返回false,因为它还没有启动。
如果您想跟踪UIWebView的成功或失败,您应该在视图控制器中实现UIWebViewDelegate。这样,当请求完成加载或失败时,就会得到回调。
发布于 2015-03-29 19:56:54
我完全不确定UIWebView是如何加载其数据的,或者调用loadRequest时到底发生了什么,但与我的预期相反,在调用loadRequest的方法返回之前,似乎什么事情都没有发生。
考虑以下代码:
@IBAction func buttonPress(sender: UIButton) {
let webview = UIWebView(frame: self.view.bounds)
view.addSubview(webview)
let url = NSURL(string: "http://www.google.com")
webview.delegate = self
webview.loadRequest(NSURLRequest(URL: url!))
println("buttonPress: webview.loading? \(webview.loading)")
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
println("webview asking for permission to start loading")
return true
}
func webViewDidStartLoad(webView: UIWebView) {
println("webview did start loading")
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
println("webview did fail load with error: \(error)")
}
func webViewDidFinishLoad(webView: UIWebView) {
println("webview did finish load!")
}在这里,buttonPress方法中的buttonPress总是在任何其他方法之前执行。实际上,不管我们在loadRequest调用之后放了什么样的代码,它都会在web视图询问shouldStartLoadingWithRequest:之前执行。
webview.loadRequest(NSURLRequest(URL: url!))
for _ in 1...10000 {
println("buttonPress: webview.loading? \(webview.loading)")
} 一万次迭代,但是直到buttonPress方法返回之后,Ten视图才会开始。
同时,webview.loading只会在webViewDidStartLoad和加载可以停止的两种方法中的一种(失败/成功) (webView(webView:didFailLoadWithError:)或webViewDidFinishLoad())之间返回webViewDidStartLoad。
如果您实现了UIWebViewDelegate协议并设置了web视图的委托,您可以实现这些方法来跟踪加载过程。如果由于任何原因,您的web视图没有加载URL,那么实现webView(webView:didFailLoadWithError:)是获得任何类型的诊断信息以确定加载失败的唯一方法。
https://stackoverflow.com/questions/29333412
复制相似问题