我尝试在现有网站上加载webView。
我在导航栏上添加了具有网址链接的按钮:
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
var myHTMLString = ""
guard let myURL = URL(string: domainURLString) else {
print("Error: \(domainURLString) doesn't seem to be a valid URL")
return
}
do {
myHTMLString = try String(contentsOf: myURL, encoding: .utf8)
} catch let error {
print("Error: \(error)")
}
webView.frame = view.bounds
webView.scalesPageToFit = true
createBottomNavigationBar()
webView.loadHTMLString(myHTMLString as String, baseURL: nil)
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print("===============================start===============================")
let myURLString:String = (request.url?.absoluteString)!
var myHTMLString = ""
if navigationType == UIWebViewNavigationType.linkClicked {
print("link clicked")
webView.stopLoading()
var myHTMLString = ""
let myURL = URL(string: myURLString)
do {
myHTMLString = try String(contentsOf: myURL!, encoding: .utf8)
} catch let error {
print("Error: \(error)")
return true
}
webView.loadHTMLString(myHTMLString as String, baseURL: nil)
print("first")
print(request.url)
}else if(navigationType == UIWebViewNavigationType.other){
print("This is for Navigation Button click")
//webView.loadHTMLString(myHTMLString as String, baseURL: nil)
}
else{
print("else")
}
return true
但是,当我取消注释时
webView.loadHTMLString(myHTMLString as String, baseURL: nil)
在此声明中:
}else if(navigationType == UIWebViewNavigationType.other){
应用程序永远循环。
该声明适用于其中一个导航按钮点击时。它重定向到内部网址,例如" http://yahoo.com/mail"。
答案 0 :(得分:1)
这将是基于您的代码的预期行为。这条线
webView.loadHTMLString(myHTMLString as String, baseURL: nil)
viewDidLoad
中的将尝试加载HTML。这反过来将调用委托方法
webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
在委托方法中,当您的代码遇到else if
案例时,它会再次调用
webView.loadHTMLString(myHTMLString as String, baseURL: nil)
反过来又会再次调用委托方法。这是一个周期性的循环。代码正常运行。你需要改变逻辑。