DEV Community

Stellan Haglund πŸš€
Stellan Haglund πŸš€

Posted on • Originally published at stellanhaglund.com

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.

Top comments (0)