I was wondering how I could subclass UIWebView to append every link the user goes to with a string at the end like "=Human". To be clear, if the user goes to Yahoo.com and then clicks on any link it will still have the "=Human" at the end.
Asked
Active
Viewed 492 times
0
-
No need. you can check navigation type. http://stackoverflow.com/a/36436728/2303865 – Leo Dabus Apr 09 '16 at 01:48
-
@LeoDabus But that just checks with a bool. Is there a method i can call and return the URL i want (like the appended one). – jordanbana Apr 09 '16 at 03:00
-
you need to show what you are trying to accomplish. Just add that suffix to the url absoluteString is pretty simple – Leo Dabus Apr 09 '16 at 03:27
-
@LeoDabus haven't been successful in getting it to work. I just want every link clicked in the webview to have this "=Human" added at the end of the URL before its loaded. – jordanbana Apr 09 '16 at 03:37
-
check this one http://stackoverflow.com/a/36231713/2303865 – Leo Dabus Apr 09 '16 at 03:41
1 Answers
0
I could subclass UIWebView
But the docs say:
A WKWebView object displays interactive web content, such as for an in-app browser.
For new development, employ this class instead of the older UIWebView class.
This works for me:
import UIKit
import WebKit
class WebViewController: UIViewController,
WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
let webView = WKWebView()
webView.navigationDelegate = self
view = webView
let defaultUrl = NSURL(
string: "https://www.yahoo.com"
)
if let validDefaultUrl = defaultUrl {
let yahooRequest = NSURLRequest(URL: validDefaultUrl)
webView.loadRequest(yahooRequest)
}
}
//MARK: - WKNavigationDelegate methods:
func webView(webView: WKWebView,
decidePolicyForNavigationAction navigationAction: WKNavigationAction,
decisionHandler: (WKNavigationActionPolicy) -> Void)
{
print("[me]: In WKWebView delegate method")
if navigationAction.navigationType == .LinkActivated {
print("[me]: User clicked on a link.")
let request = navigationAction.request
if let url = request.URL,
newURL = NSURL(string: url.absoluteString + "=User")
{
print("[me]: New url is valid.")
print("[me]: New url is \(newURL.absoluteString)")
let newRequest = NSMutableURLRequest(URL: newURL)
decisionHandler(.Cancel)
webView.loadRequest(newRequest)
}
}
decisionHandler(.Allow)
}
}
Edit: Actually, the code does not enter the if navigationAction.navigationType == .LinkActivated
block every time a link is clicked for some reason. Sometimes I see just the output:
[me]: In WKWebView delegate method
and I fail to see the output:
[me]: User clicked on a link.

7stud
- 46,922
- 14
- 101
- 127
-
@LeoDabus, I'm an iOS beginner and I cobbled that code together by mysellf looking only at the Apple docs and my BNR IOS book. I'd like to know why it doesn't work. – 7stud Apr 09 '16 at 20:17