How to Create Custom URL Schemes in a WKWebView in Swift

WKWebView is a powerful component for displaying web content in your Swift iOS applications. One of its key features is the ability to communicate between your app and web content using custom URL schemes. Custom URL schemes enable you to define specific URLs that, when clicked, trigger actions or communication within your app. In this article, we’ll explore how to create and use custom URL schemes with WKWebView in Swift.

Understanding Custom URL Schemes

A custom URL scheme is a unique URL format that is not part of the standard HTTP or HTTPS protocol. It allows you to define URLs specific to your app, and when users interact with these URLs, your app can capture and respond to them.

Creating a Custom URL Scheme

To create a custom URL scheme for your iOS app, follow these steps:

  1. Open your Xcode project.
  2. Select your project in the project navigator.
  3. Choose your app target.
  4. Go to the “Info” tab.
  5. Under “URL Types,” click the “+” button to add a new URL type.
  6. In the “URL Identifier” field, provide a unique identifier, such as com.yourcompany.myapp.
  7. In the “URL Schemes” field, specify the custom scheme you want to use, such as myapp.

Using the Custom URL Scheme

With the custom URL scheme set up, you can now use it within your WKWebView to enable communication between your app and web content.

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        let webView = WKWebView(frame: view.frame)
        webView.navigationDelegate = self
        view.addSubview(webView)

        // Load a web page that contains links with your custom URL scheme
        if let url = URL(string: "https://example.com") {
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }

    // WKNavigationDelegate method to handle custom URL scheme navigation
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url, url.scheme == "myapp" {
            // Handle the custom URL scheme here
            // Example: Extract parameters and perform an action
            let parameters = url.queryParameters
            let action = parameters["action"]

            // Perform an action based on the URL parameters
            if action == "doSomething" {
                // Do something in your app
            }

            // Cancel the navigation, as we've handled the custom URL scheme
            decisionHandler(.cancel)
            return
        }

        // Allow standard web navigation
        decisionHandler(.allow)
    }
}

// Extension to parse query parameters from a URL
extension URL {
    var queryParameters: [String: String] {
        guard let query = self.query else {
            return [:]
        }
        return query.components(separatedBy: "&")
            .reduce(into: [:]) { result, keyValue in
                let keyValueArray = keyValue.components(separatedBy: "=")
                if keyValueArray.count == 2 {
                    let key = keyValueArray[0]
                    let value = keyValueArray[1]
                    result[key] = value
                }
            }
    }
}

In the code example above, we create a custom URL scheme myapp and use it in a WKWebView. The WKNavigationDelegate is used to intercept navigation actions and handle custom URL schemes. When a URL with the myapp scheme is clicked, you can extract parameters from the URL and perform specific actions in your app.

Custom URL schemes are a powerful way to bridge the gap between web content and your app, allowing for deep integration and custom interactions.

Conclusion

Creating and using custom URL schemes in a WKWebView is a valuable feature for enhancing the interaction between web content and your iOS app. By following these steps, you can define your custom URL schemes and handle them within your app, enabling unique interactions and user experiences.

Whether you want to trigger specific actions, communicate data, or integrate with web services, custom URL schemes provide a versatile way to make your WKWebView-based app more dynamic and responsive.

A pat on the back !!