# Integrating Popin WebView into Your iOS App

#### 🧩 Step 1: Add Required Permissions

In your **Info.plist**, add:

```xml
<key>NSCameraUsageDescription</key>
<string>Camera access is required for video calls.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Microphone access is required for audio during calls.</string>
```

***

#### 🧱 Step 2: Create PopinWebViewController.swift

This view controller hosts the Popin WebView and automatically prompts for camera/mic access when requested by the web content.

```swift
import UIKit
import WebKit
import AVFoundation

class PopinWebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    private var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupWebView()
        loadPopinWidget()
    }

    private func setupWebView() {
        let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        if #available(iOS 10.0, *) {
            config.mediaTypesRequiringUserActionForPlayback = []
        }

        webView = WKWebView(frame: view.bounds, configuration: config)
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view.addSubview(webView)
    }

    private func loadPopinWidget() {
        let urlString = "https://widget01.popin.to/standalone?token=XXXXX&popin=open"
        if let url = URL(string: urlString) {
            webView.load(URLRequest(url: url))
        }
    }

    // Handles permission requests from the web page
    func webView(_ webView: WKWebView,
                 requestMediaCapturePermissionFor origin: WKSecurityOrigin,
                 initiatedByFrame frame: WKFrameInfo,
                 type: WKMediaCaptureType,
                 decisionHandler: @escaping (WKPermissionDecision) -> Void) {

        // Check and request iOS permissions first
        switch type {
        case .camera:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                decisionHandler(granted ? .grant : .deny)
            }
        case .microphone:
            AVCaptureDevice.requestAccess(for: .audio) { granted in
                decisionHandler(granted ? .grant : .deny)
            }
        default:
            decisionHandler(.deny)
        }
    }
}
```

***

#### 📲 Step 3: Present the Popin WebView

From any view controller, you can launch it like:

```swift
let vc = PopinWebViewController()
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
```

***

#### ✅ Notes

* `requestMediaCapturePermissionFor` is available on **iOS 15+** and automatically triggers when a web page (like Popin) requests access to camera/mic via WebRTC.
* The `decisionHandler` must be called with `.grant` or `.deny` based on the user’s iOS permission status.
* This approach ensures your WebView and app stay in sync with system-level permission prompts.
