我在webview应用程序iOS swift中工作:
我面临的问题是我想获得webview显示的每个网址:
在网址上我必须执行一些if else检查。但我无法得到webview加载的网址。
webview正在显示精细结果并在点击时加载网址。我想获取webview导航的所有网址..
import Foundation
import UIKit
class seconVC: UIViewController {
var toPass:String!
var touser:String!
var toPassing:String!
@IBOutlet weak var webV: UIWebView!
@IBOutlet weak var L_back: UIBarButtonItem!
@IBOutlet weak var R_frwrd: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var domurl = toPass;
var username = touser;
var passwing = toPassing;
var sendurl = stringA+username+"/"+passwing;
//exchange login with auth/username/password
println(sendurl);
let url = NSURL (string: sendurl);
let requestObj = NSURLRequest(URL: url!);
webV.userInteractionEnabled = true
webV.loadRequest(requestObj);
}
@IBAction func L_back(sender: UIBarButtonItem) {
if (webV.canGoBack){
webV.goBack()
}
}
@IBAction func R_frwrd(sender: UIBarButtonItem) {
if (webV.canGoForward){
webV.goForward()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我想要的是获取webview的当前网址和导航按钮的字符串:请帮忙吗?我提到所有的互联网没有解决方案在我的情况下工作。
答案 0 :(得分:6)
有UIWebViewDelegate
个shouldStartLoadWithRequest
,例如webViewDidStartLoad
或webViewDidFinishLoad
或didFailLoadWithError
或if let currentURL = webView.request?.url?.absoluteString{
print(currentURL)
}
可帮助您实现目标。如果要在视图完成后执行操作,请实现此委托方法
Swift 3
mailto:
提到here。
答案 1 :(得分:5)
选项-1 强>
let currentURL = webV.request.URL.absoluteString
选项-2 强>
在委托方法中获取网址
func webViewDidFinishLoad(webView: UIWebView){
print(WebView.request?.mainDocumentURL)
}
选项-3 强>
func webViewDidFinishLoad(webView: UIWebView) {
let currentURL = webView.request().URL()
print("\(currentURL.description)")
}
或使用
func webViewDidFinishLoad(webView: UIWebView){
let currentURL = webView.request?.URL
}
选项-4 强>
func webViewDidFinishLoad(webView: UIWebView) {
let currentURL: = webView.stringByEvaluatingJavaScriptFromString("window.location.href")!
print("\(currentURL)")
}
选项-5 强>
func webView(webview: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let currentURL = request.URL.absoluteString
print("\(currentURL)")
}
选项-6 强>
func webViewDidFinishLoad(WebVie: UIWebView) {
let currentURL = WebVie.request.mainDocumentURL
print("\(currentURL)")
}
答案 2 :(得分:0)
首先,您必须定义WebView类的委托。 “ WebView.delegate =自我”。将此代码添加到上述功能之一旁边:
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self }
,例如:
func webViewDidFinishLoad(_ webView: UIWebView) {
if let currentURL = WebView.request?.url?.absoluteString{
print(currentURL)
}
}