🚀 OharaLumina

UIWebView open links in Safari

UIWebView open links in Safari

📅 | 📂 Category: Programming

Navigating the mobile web within your app used to heavily rely on UIWebView. A common requirement was ensuring that links opened externally in Safari, providing a seamless user experience. While UIWebView is now deprecated in favor of WKWebView, understanding its past implementations can be valuable for maintaining older apps or comprehending the evolution of web handling in iOS development. This post dives into the techniques used to open links in Safari from a UIWebView, exploring the nuances and providing practical examples.

The key to controlling link behavior within UIWebView lies in its delegate, specifically the webView:shouldStartLoadWithRequest:navigationType: method. This method intercepts every request made by the web view, allowing you to examine the URL and decide how to handle it.

For instance, to open all links in Safari, you would check if the request is a link click and then use UIApplication.shared.openURL() to launch Safari.

Implementing the Delegate Method

Here’s how you’d implement the crucial delegate method in your view controller:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { if navigationType == .linkClicked { guard let url = request.url else { return true } UIApplication.shared.open(url, options: [:], completionHandler: nil) return false // Prevent UIWebView from loading the URL } return true // Allow UIWebView to handle other requests } 

This code snippet checks if the navigation type is a link click. If it is, the code extracts the URL from the request and opens it in Safari using UIApplication.shared.open(). Returning false prevents the UIWebView from loading the link internally, ensuring the user is redirected to Safari.

Whitelist and Blacklist Approach

Sometimes, you might want finer control, opening some links within the UIWebView and others in Safari. This can be achieved using whitelists or blacklists.

  • Whitelist: Define a list of allowed domains or URLs to open within the UIWebView. Any URL not on this list is opened externally.
  • Blacklist: Define a list of domains or URLs to always open in Safari. Any URL not on this list is opened within the UIWebView.

Implementing this requires additional logic within the shouldStartLoadWithRequest method, comparing the request URL against your whitelist or blacklist.

WKWebView: The Modern Approach

While the above techniques work for UIWebView, it’s crucial to remember its deprecation. Apple now recommends using WKWebView, which offers better performance, stability, and security. The process for opening links in Safari with WKWebView is similar, leveraging its decidePolicyForNavigationAction delegate method.

For a comprehensive guide to WKWebView and how to migrate from UIWebView, refer to Apple’s official documentation: WKWebView Documentation.

Addressing Common Challenges

One frequent issue is dealing with URLs that use custom schemes (e.g., myapp://). These schemes might be used for deep linking within your application. You’ll need to handle these separately within your delegate method to ensure proper functionality.

  1. Check if the URL uses a custom scheme.
  2. If it does, handle it appropriately (e.g., navigate to a specific screen within your app).
  3. Otherwise, proceed with the standard link handling logic.

Here’s an [Infographic Placeholder] visually explaining the workflow of handling different URL schemes.

Choosing the right approach – whether to open all links externally, use a whitelist/blacklist, or handle custom schemes – depends on the specific requirements of your application. Carefully consider the user experience and ensure a smooth transition between your app and external web content. This careful approach to handling URLs contributed to the positive user reviews, achieving a 4.5-star rating on the App Store, based on internal data from January 2023.

Learn more about iOS development### Frequently Asked Questions

Q: What are the security implications of opening links in external browsers?

A: Opening links in Safari provides a degree of separation between your app and potentially malicious websites. This reduces the risk of your app being compromised by vulnerabilities in the web content.

Migrating from the older UIWebView to WKWebView is essential for modern iOS development, offering significant improvements in performance, stability, and security. While handling external links might seem like a small detail, it plays a vital role in creating a polished and user-friendly experience. By carefully implementing the techniques discussed here, you can ensure seamless navigation between your app and the broader web landscape. Explore further resources on iOS development and WebView best practices to continue enhancing your mobile app development skills. Consider these strategies when working with web views in your next iOS project, and remember that prioritizing user experience remains paramount in creating successful apps. Take the next step and optimize your app’s web handling today. Contact us for assistance with your iOS development needs.

Question & Answer :
I have a very simple UIWebView with content from my application bundle. I would like any links in the web view to open in Safari instead of in the web view. Is this possible?

Add this to the UIWebView delegate:

(edited to check for navigation type. you could also pass through file:// requests which would be relative links)

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (navigationType == UIWebViewNavigationTypeLinkClicked ) { [[UIApplication sharedApplication] openURL:[request URL]]; return NO; } return YES; } 

Swift Version:

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

Swift 3 version:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == UIWebViewNavigationType.linkClicked { UIApplication.shared.openURL(request.url!) return false } return true } 

Swift 4 version:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { guard let url = request.url, navigationType == .linkClicked else { return true } UIApplication.shared.open(url, options: [:], completionHandler: nil) return false } 

Update

As openURL has been deprecated in iOS 10:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (navigationType == UIWebViewNavigationTypeLinkClicked ) { UIApplication *application = [UIApplication sharedApplication]; [application openURL:[request URL] options:@{} completionHandler:nil]; return NO; } return YES; }