从Webview中的链接获取参数

时间:2016-12-19 13:51:34

标签: ios webview swift3 permalinks

我在viewController中创建了一个webview并加载了一个像这样的页面

func loadAddress(){
    let requestURL = NSURL(string:"http://www.example.com/")
    let request = NSURLRequest(url: requestURL as! URL)
    webview.loadRequest(request as URLRequest)
}

中调用它
  

viewDidLoad中

我在页面中有一些带有URL参数的链接

http://www.example.com?id=1&title=ABC

现在,当用户从应用中点击此链接,而不是重定向到URL时,我想从URL获取参数并在iOS中打开一个对话框

我在Objective C中找到了一些示例,但我正在寻找Swift 3中的解决方案

PS:我可以访问此网站的HTML我可以根据Xcode的要求替换链接

编辑:这是我试过的,在我写的这个函数我的webview的同一个文件中

func webView(_ webView: UIWebView,shouldStartLoadWith request: URLRequest,navigationType: UIWebViewNavigationType) -> Bool {

    let scheme = request.url!
    NSLog(scheme.absoluteString)

    return false

}

并确保该类是webview的委托

enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您应该使用webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool方法,该方法将URLRequest作为参数。 在这种方法中,您可以对该URL执行任何操作。

不要忘记将您的课程设置为网络视图的代表。

如果您想使用查询字符串,可以从此objective-c answer

中获取灵感

答案 1 :(得分:0)

我自己找到了一个解决方案,我编写的代码是正确的,我只需要确保我的类也实现了UIWebViewDelegate

所以班级看起来像这样

class Mainbillboard: UIViewController,UIWebViewDelegate {


@IBOutlet weak var activity: UIActivityIndicatorView!
@IBOutlet weak var webview: UIWebView!


override func viewDidLoad() {
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    loadAddress()
}

func loadAddress(){
    let requestURL = NSURL(string:"example.com")
    let request = NSURLRequest(url: requestURL as! URL)
    webview.loadRequest(request as URLRequest)

}

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    let scheme = request.url!
    NSLog(scheme.absoluteString)
    NSLog("here it worked!!")

    return true

}


func webViewDidStartLoad(_:UIWebView){
    self.view.bringSubview(toFront: self.activity)
    activity.startAnimating()
    NSLog("Indicator is loading")

}

func webViewDidFinishLoad(_:UIWebView){
    activity.stopAnimating()
    NSLog("Indicator stopped loading")
}

}
相关问题