0

I try to create own links with own actions in a UIWebView. For that I like to read the value of my own links. I manage to do, but I would like someone would have a review on this, because I am not sure if this is best practice ? :-) (messy code ?)

I create my own HTML with some own links like :

let myHTML:String="<a href=\"mylink:" + sLinkValue + "\">" + sDisplayText + "</a>";

I created a UIWebView and show the HTML:

myWebView.loadHTMLString(htmlString, baseURL: noBase);

with a delegate UIWebViewDelegate my delegate is called when a link is clicked:

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    let requestdescription:String = request.description;
    println(requestdescription);
    let Valueonly:String=getValueOnly(requestdescription);
    println(Valueonly);
    return true
}

In above Code my requestdescription has the following value: <NSMutableURLRequest: 0x7fad4ae21130> { URL: mylink:My%20own%20Value }

and getValueOnly which cuts and pasts the requestdescription returns "My Own Value"

Is this the way we should do it ?

mcfly soft
  • 11,289
  • 26
  • 98
  • 202

2 Answers2

0

There is no official API for calling obj-c code from UIWebView and your approach is viable. However, there are some more versatile methods of doing this:

Community
  • 1
  • 1
Jakub Vano
  • 3,833
  • 15
  • 29
0

I would suggest to use request.URL.host instead of retrieving it with auxiliary function and check if request.URL.scheme isEqualToString "my link" to be sure it's not some normal request. By the way, you probably don't want any requests with your custom scheme to be really performed, so return false to avoid this.

user2260054
  • 522
  • 1
  • 3
  • 11
  • Thanks for this explanation. Espacially Scheme and retuning false in case its not the right scheme is helpfull. – mcfly soft Apr 24 '15 at 09:41
  • You're welcome! I also used this approach several times in my apps, hope something more elegant will be available in future. – user2260054 Apr 24 '15 at 11:01