Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit UIWebView to specific URL (Swift)

I'm trying to develop an iOS app that features a UIWebView in Swift, however I need it to only work with one domain, and any external links clicked on in that UIWebView to be opened in Safari. (E.G. All links to http://example.com will open within the UIWebView, but a link to http://twitter.com would open in Safari).

I have found a couple of solutions online but the only Swift version (found here: UIWebView open links in Safari) works to open every link in Safari, I just want external ones to do so.

Could anyone help? Thanks.

like image 919
MattFiler Avatar asked Dec 15 '22 17:12

MattFiler


2 Answers

As @MattFlier's solution is correct but doesn't compile with the latest Swift compiler. It's important to unwrap the NSURLRequest URL property so the updated solution is:

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    if navigationType == UIWebViewNavigationType.LinkClicked {
        if (request.URL!.host! == "example.com"){
            return true
        } else {
            UIApplication.sharedApplication().openURL(request.URL!)
            return false
        }
    }
    return true
}

And yes, to hook this up you can Control+Drag your UIWebView to the UIViewController that is representing the view, and then make sure the delegate function is named the same as the "IBOutlet weak var", like so

What this looks like

You also need to make sure your view controller implements UIWebViewDelegate

class OfferDetailViewController : UIViewController, UIWebViewDelegate
{
    ...

And then in your viewDidLoad() method you also need to assign the delegate like so:

override func viewDidLoad() {
    self.webView.delegate = self;
}
like image 196
Ben H Avatar answered Mar 02 '23 21:03

Ben H


I must be getting better at Swift than I thought...

Modifying the solution that I found originally (linked in the question), I came up with this alternative that allows through my URL, but opens any external URLs in Safari.

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    if navigationType == UIWebViewNavigationType.LinkClicked {
        if (request.URL.host! == "example.com"){
            return true
        } else {
            UIApplication.sharedApplication().openURL(request.URL)
            return false
        }
    }
    return true
}

Don't forget to delegate this code from the UIWebView to the View Controller, and it should work fine (just as long as you replace example.com with your URL.

Please vote up this comment, as I have spent all day searching through tutorials and forums, and think that my final solution is a pretty clean one!

like image 26
MattFiler Avatar answered Mar 02 '23 20:03

MattFiler