UIWebView
Safari
iOS development
open links
mobile browsing

UIWebView open links in Safari

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In the early days of iOS development, UIWebView was the primary class developers used to display web content within an application. Over time, with more sophisticated web technologies and user experience expectations, certain scenarios required opening links directly in Safari, Apple's native web browser. This article delves into techniques for handling such scenarios, emphasizing the transition mechanisms from in-app browsing to full web experiences in Safari.

UIWebView Overview

UIWebView is a part of UIKit and allows apps to embed a web browser directly. Although UIWebView has been deprecated in favor of WKWebView, understanding its mechanics is essential for legacy support.

Some key features of UIWebView include:

  • Embedding HTML content.
  • Executing JavaScript within a webpage.
  • Navigating through web pages with back and forward controls.

Sometimes, developers need to direct users away from the app to open certain links in Safari due to complex web page requirements or to maintain session and cookies across native and browser environments. By default, UIWebView handles link clicks internally, preventing external navigation.

Implementing UIWebViewDelegate

To intercept link clicks, developers can use the UIWebViewDelegate protocol. This protocol provides methods to manage various web view interactions.

Example Implementation

Here’s a sample implementation demonstrating how to open external links in Safari:

objc
1- (BOOL)webView:(UIWebView *)webView 
2    shouldStartLoadWithRequest:(NSURLRequest *)request 
3    navigationType:(UIWebViewNavigationType)navigationType {
4    
5    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
6        // Determine if you wish to open the URL in Safari
7        if (/* Condition to open in Safari */) {
8            [[UIApplication sharedApplication] openURL:request.URL];
9            return NO;
10        }
11    }
12    return YES; // Continue loading inside the app
13}

In this code snippet, the shouldStartLoadWithRequest method determines if a link click (UIWebViewNavigationTypeLinkClicked) should result in navigation within the app or by launching Safari.

Transitioning to WKWebView

Apple introduced WKWebView in iOS 8, providing a more modern and performance-optimized way to display web content. Transitioning to WKWebView is advisable due to:

  • Improved performance and memory management.
  • Support for additional features like WebRTC, service workers, and enhanced caching.
  • Superior debugging capabilities.

Key Differences Between UIWebView and WKWebView

FeatureUIWebViewWKWebView
PerformanceSub-optimal performanceHigh performance with optimized rendering
DeprecatedYesNo
Modern Web FeaturesLimitedFull support
JavaScript ExecutionSynchronousAsynchronous via WKScriptMessageHandler
Delegation ModelUIWebViewDelegateWKNavigationDelegate, WKUIDelegate
Use in New ProjectsNot recommendedHighly recommended

WKWebView also provides mechanisms to intercept and handle link clicks. The WKNavigationDelegate includes methods like decidePolicyForNavigationAction. This allows for a similar approach to determining whether a URL should be handled in-app or sent to Safari.

Example with WKWebView

swift
1func webView(_ webView: WKWebView, 
2             decidePolicyFor navigationAction: WKNavigationAction, 
3             decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
4    
5    if navigationAction.navigationType == .linkActivated {
6        if let url = navigationAction.request.url {
7            // Example condition to open in Safari
8            if url.host == "www.example.com" {
9                UIApplication.shared.open(url)
10                decisionHandler(.cancel)
11                return
12            }
13        }
14    }
15    
16    decisionHandler(.allow)
17}

Using WKWebView, decisions regarding URL handling are synchronous, meaning the app can decide on the fly the appropriate course of action for each navigation event.

Conclusion

While UIWebView served as a robust solution for embedding web content, its limitations and deprecation have prompted developers to transition towards WKWebView, which stands as the modern standard. An understanding of transitioning from UI-based web handling to Safari provides flexibility and enhances user experience, especially when dealing with advanced or resource-heavy web pages. Remember to consider user scenarios and security implications when deciding when and how to open links externally in Safari.


Course illustration
Course illustration

All Rights Reserved.