How to allow webview camera and microphone access from swift

stellanhaglund

Stellan Haglund 🚀

Posted on January 25, 2023

How to allow webview camera and microphone access from swift

With the release of iOS 15, Apple introduced the ability to request media capture permission directly from the WKWebView. This allows developers to have more control over how and when the user is prompted for camera and microphone access.

To implement this feature, we will first need to implement the a WKUIDelegate method To your ViewController This method is called when the WKWebView encounters a request for camera or microphone access from a website.

Here's how it looks.

    @available(iOS 15, *)
    func webView(
        _ webView: WKWebView,
        requestMediaCapturePermissionFor origin: WKSecurityOrigin,
        initiatedByFrame frame: WKFrameInfo,
        type: WKMediaCaptureType,
        decisionHandler: @escaping (WKPermissionDecision) -> Void
    ) {
        decisionHandler(.grant)
    }
Enter fullscreen mode Exit fullscreen mode

You also need to add the WKUIDelegate to your ViewController and set
webView.uiDelegate = self and your done.

No more permission request from the webview. 🎉

A good thing to note though is that this will allow permissions from all sites, you should probably limit it to use only the url's you want.

💖 💪 🙅 🚩
stellanhaglund
Stellan Haglund 🚀

Posted on January 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related