乐闻世界logo
搜索文章和话题

How open link in safari mobile app from webview

1个答案

1

In iOS development, opening links from a WebView typically involves determining the target URL of the link and deciding whether to load it within the current WebView or open it in an external browser (such as Safari). The following are the specific steps to implement opening links in Safari when clicked within the WebView:

Step 1: Set up the WebView delegate

First, ensure that your WebView has a delegate configured so you can receive and handle events from the WebView. If you are using WKWebView, you must conform to the WKNavigationDelegate protocol.

swift
import WebKit class ViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() // Initialize the WebView webView = WKWebView(frame: self.view.bounds) webView.navigationDelegate = self self.view.addSubview(webView) // Load a webpage if let url = URL(string: "https://www.example.com") { webView.load(URLRequest(url: url)) } } }

Implement the webView(_:decidePolicyFor:decisionHandler:) method of WKNavigationDelegate to intercept links. Within this method, determine whether the link should be opened in Safari. If so, use the open(_:options:completionHandler:) method of UIApplication to open the link in Safari.

swift
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.url, navigationAction.navigationType == .linkActivated { // Check if the URL needs to be opened in Safari if shouldOpenInSafari(url: url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) decisionHandler(.cancel) } else { decisionHandler(.allow) } } else { decisionHandler(.allow) } } func shouldOpenInSafari(url: URL) -> Bool { // Determine whether to open in Safari based on actual requirements // For example, detect if the URL's domain is not within the application's managed scope return !url.host!.contains("example.com") }

Example Scenario

Suppose your application has an embedded help page containing many external links. When users click these links, you want them to open in Safari rather than load within the current WebView. The above code snippet achieves this by determining whether to open in Safari based on the link's domain not being 'example.com'.

This approach enhances user experience, especially for external resources, as users often prefer opening links in a full-featured browser to utilize built-in features like bookmarks and history. Additionally, it prevents loading external web pages that may be incompatible or display incorrectly within the app.

2024年8月8日 14:25 回复

你的答案