Pleased logoDocs

Integrating the Chatbot into your iOS application

Last edited 12/11/2026 by Divyank Mishra

You can show the Pleased Chat Widget inside your iOS app. Your app opens a screen with a WKWebView, and the WKWebView loads a page that Pleased hosts for you. You do not need a website of your own.

This article is for the iOS developer adding the widget. It covers the chat itself, signing in your users, file attachments and voice calls.


Before you begin

  • An Xcode project with deployment target iOS 15 or higher. The integration uses an iOS 15 WebKit API and does not compile on older deployment targets. You do not need CocoaPods or other packages.
  • A Chat Widget created in Pleased. See Install the Pleased Chat Widget on your website for how to create one.
  • Your client ID and widget ID from the generated Chat Widget code: data-pls-client-id and data-pls-widget-id.
Important: Use the IDs from the code generated for your Chat Widget in Pleased. Do not copy the example values from this article.

Step 1: Add the usage descriptions

Add both keys to your app’s Info.plist (or the target Info tab in Xcode):

<key>NSMicrophoneUsageDescription</key>
<string>We use the microphone for voice support in the chat.</string>
<key>NSCameraUsageDescription</key>
<string>We use the camera so you can send a photo in the chat.</string>

iOS shows these on its permission prompts.

Important: NSCameraUsageDescription is required for attachments. The chat’s attach control accepts images, so on a real iPhone the system picker offers Take Photo. WebKit shows that option without checking the plist first; tapping it without NSCameraUsageDescription crashes the app. The Simulator has no camera, so you will not see this there.

Without NSMicrophoneUsageDescription, microphone requests are refused and no prompt appears (WebKit checks for the key). Skip the microphone key only if you will never use voice calls.


Step 2: Add the two Swift files

Copy both files into your Xcode project as they are.

PleasedWebViewSetup.swift

Configures the WKWebView, answers microphone requests (iOS 15+), and opens off-site links in Safari.

import Foundation
import SafariServices
import UIKit
import WebKit

/// WebView setup for the Pleased chatbot. Copy this file as-is.
final class PleasedWebViewSetup: NSObject {
    static let defaultWidgetOrigins: Set<String> = ["https://cdn.pleased.com"]

    private weak var webView: WKWebView?
    private let widgetOrigins: Set<String>
    private var pinnedUrl: String?

    init(webView: WKWebView, widgetOrigins: Set<String> = PleasedWebViewSetup.defaultWidgetOrigins) {
        self.webView = webView
        self.widgetOrigins = widgetOrigins
        super.init()
    }

    /// Apply before `WKWebView(frame:configuration:)`. Playback options are read at construction.
    static func applyMediaPlaybackPolicy(to configuration: WKWebViewConfiguration) {
        configuration.allowsInlineMediaPlayback = true
        if #available(iOS 10.0, *) {
            configuration.mediaTypesRequiringUserActionForPlayback = []
        }
        if #available(iOS 16.4, *) {
            configuration.preferences.isElementFullscreenEnabled = true
        }
    }

    func configure() {
        guard let webView else { return }
        #if DEBUG
        if #available(iOS 16.4, *) {
            webView.isInspectable = true
        }
        #endif

        webView.navigationDelegate = self
        webView.uiDelegate = self
    }

    static func origin(of urlString: String?) -> String? {
        guard let urlString,
              let url = URL(string: urlString),
              let scheme = url.scheme,
              let host = url.host
        else { return nil }
        if let port = url.port {
            return "\(scheme)://\(host):\(port)"
        }
        return "\(scheme)://\(host)"
    }

    private func withoutFragment(_ url: String) -> String {
        url.split(separator: "#", maxSplits: 1).first.map(String.init) ?? url
    }

    private func leaveWebView(_ url: String) {
        guard let url = URL(string: url) else { return }
        DispatchQueue.main.async {
            UIApplication.shared.open(url)
        }
    }

    func answerMediaCapture(
        origin: WKSecurityOrigin,
        type: WKMediaCaptureType,
        decisionHandler: @escaping (WKPermissionDecision) -> Void
    ) {
        guard type == .microphone else {
            decisionHandler(.deny)
            return
        }
        let asking = Self.origin(from: origin)
        let pinnedOrigin = Self.origin(of: pinnedUrl)
        if asking == nil || (asking != pinnedOrigin && !widgetOrigins.contains(asking ?? "")) {
            decisionHandler(.deny)
            return
        }
        decisionHandler(.grant)
    }

    static func origin(from securityOrigin: WKSecurityOrigin) -> String? {
        let host = securityOrigin.host
        if host.isEmpty { return nil }
        if securityOrigin.port == 0 {
            return "\(securityOrigin.protocol)://\(host)"
        }
        return "\(securityOrigin.protocol)://\(host):\(securityOrigin.port)"
    }
}

extension PleasedWebViewSetup: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if pinnedUrl == nil {
            pinnedUrl = withoutFragment(webView.url?.absoluteString ?? "")
        }
    }

    func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationAction: WKNavigationAction,
        decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
    ) {
        if navigationAction.targetFrame == nil {
            if let target = navigationAction.request.url?.absoluteString {
                leaveWebView(target)
            }
            decisionHandler(.cancel)
            return
        }
        guard navigationAction.targetFrame?.isMainFrame == true else {
            decisionHandler(.allow)
            return
        }
        let pinned = pinnedUrl
        guard let pinned, let target = navigationAction.request.url?.absoluteString else {
            decisionHandler(.allow)
            return
        }
        if withoutFragment(target) == pinned {
            decisionHandler(.allow)
            return
        }
        leaveWebView(target)
        decisionHandler(.cancel)
    }

    func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationResponse: WKNavigationResponse,
        decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
    ) {
        guard navigationResponse.isForMainFrame else {
            decisionHandler(.allow)
            return
        }
        let pinned = pinnedUrl
        guard let pinned, let target = navigationResponse.response.url?.absoluteString else {
            decisionHandler(.allow)
            return
        }
        if withoutFragment(target) == pinned {
            decisionHandler(.allow)
            return
        }
        leaveWebView(target)
        decisionHandler(.cancel)
    }
}

@available(iOS 15.0, *)
extension PleasedWebViewSetup: WKUIDelegate {
    func webView(
        _ webView: WKWebView,
        requestMediaCapturePermissionFor origin: WKSecurityOrigin,
        initiatedByFrame frame: WKFrameInfo,
        type: WKMediaCaptureType,
        decisionHandler: @escaping (WKPermissionDecision) -> Void
    ) {
        answerMediaCapture(origin: origin, type: type, decisionHandler: decisionHandler)
    }
}

PleasedBridge.swift

Lets your app talk to the widget: visitor token, open/close chat, events.

import Foundation
import WebKit

/// Drives the Pleased loader running inside a WKWebView. Copy this file as-is.
final class PleasedBridge: NSObject {
    typealias CallbackHandler = (_ payloadJson: String?, _ respond: Responder) -> Void

    protocol Responder: AnyObject {
        func resolve(valueJson: String?)
        func reject(error: String)
    }

    var onLoaderReady: (() -> Void)?
    var onLog: ((String) -> Void)?

    private weak var webView: WKWebView?
    private weak var userContentController: WKUserContentController?
    private let lock = NSLock()
    private var handlers: [String: CallbackHandler] = [:]

    init(configuration: WKWebViewConfiguration) {
        super.init()
        let controller = configuration.userContentController
        userContentController = controller
        controller.add(self, name: "pleasedNative")
    }

    func bind(webView: WKWebView) {
        self.webView = webView
    }

    deinit {
        userContentController?.removeScriptMessageHandler(forName: "pleasedNative")
    }

    func invoke(_ command: String, payloadJson: String? = nil, onResult: ((String) -> Void)? = nil) {
        if let payloadJson, !payloadJson.isEmpty {
            let opts: JSONSerialization.ReadingOptions = [.fragmentsAllowed]
            if (try? JSONSerialization.jsonObject(with: Data(payloadJson.utf8), options: opts)) == nil {
                let error = #"{"ok":false,"error":"payloadJson is not valid JSON"}"#
                dispatchMain { onResult?(error) }
                return
            }
        }
        let payloadPart = payloadJson.map { jsonQuote($0) } ?? "null"
        let js = "window.__plInvoke(\(jsonQuote(command)), \(payloadPart))"
        eval(js, onResult: onResult)
    }

    func registerCallback(type: String, name: String, handler: @escaping CallbackHandler) {
        lock.lock()
        handlers["\(type)|\(name)"] = handler
        lock.unlock()
        eval("window.__plAddCallback(\(jsonQuote(type)), \(jsonQuote(name)))")
    }

    func removeCallback(type: String, name: String) {
        lock.lock()
        handlers.removeValue(forKey: "\(type)|\(name)")
        lock.unlock()
        eval("window.__plRemoveCallback(\(jsonQuote(type)), \(jsonQuote(name)))")
    }

    private func eval(_ js: String, onResult: ((String) -> Void)? = nil) {
        dispatchMain {
            guard let webView = self.webView else {
                onResult?("null")
                return
            }
            webView.evaluateJavaScript(js) { value, error in
                if error != nil, onResult != nil {
                    onResult?("null")
                    return
                }
                if let onResult {
                    onResult(Self.unwrap(value))
                }
            }
        }
    }

    private func dispatchMain(_ block: @escaping () -> Void) {
        if Thread.isMainThread {
            block()
        } else {
            DispatchQueue.main.async(execute: block)
        }
    }

    private static func unwrap(_ value: Any?) -> String {
        guard let value else { return "null" }
        if let str = value as? String { return peelJsonStringIfNeeded(str) }
        if let str = value as? NSString { return peelJsonStringIfNeeded(str as String) }
        if JSONSerialization.isValidJSONObject(value),
           let data = try? JSONSerialization.data(withJSONObject: value),
           let json = String(data: data, encoding: .utf8) { return json }
        if let num = value as? NSNumber { return num.stringValue }
        return "null"
    }

    private static func peelJsonStringIfNeeded(_ value: String) -> String {
        guard let data = value.data(using: .utf8),
              let parsed = try? JSONSerialization.jsonObject(with: data)
        else { return value }
        if let inner = parsed as? String { return inner }
        return value
    }

    private func jsonQuote(_ string: String) -> String {
        guard let data = try? JSONEncoder().encode(string),
              let encoded = String(data: data, encoding: .utf8)
        else { return "\"\"" }
        return encoded
    }

    private func resolve(id: String, valueJson: String?) {
        let valuePart = valueJson.map { jsonQuote($0) } ?? "null"
        eval("window.__plResolveCallback(\(jsonQuote(id)), \(valuePart))")
    }

    private func reject(id: String, error: String) {
        eval("window.__plRejectCallback(\(jsonQuote(id)), \(jsonQuote(error)))")
    }

    private func onMain(_ block: @escaping () -> Void) { dispatchMain(block) }

    private final class JsResponder: Responder {
        private var settled = false
        private let id: String
        private weak var bridge: PleasedBridge?
        init(id: String, bridge: PleasedBridge) {
            self.id = id
            self.bridge = bridge
        }
        func resolve(valueJson: String?) {
            guard !settled else { return }
            settled = true
            bridge?.resolve(id: id, valueJson: valueJson)
        }
        func reject(error: String) {
            guard !settled else { return }
            settled = true
            bridge?.reject(id: id, error: error)
        }
    }

    private final class NoopResponder: Responder {
        static let shared = NoopResponder()
        func resolve(valueJson: String?) {}
        func reject(error: String) {}
    }
}

extension PleasedBridge: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        guard message.name == "pleasedNative",
              let body = message.body as? String,
              let data = body.data(using: .utf8),
              let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
              let kind = json["kind"] as? String
        else { return }

        switch kind {
        case "loader_ready":
            onMain { self.onLoaderReady?() }
        case "log":
            if let text = json["message"] as? String { onMain { self.onLog?(text) } }
        case "event":
            let name = json["name"] as? String ?? ""
            let via = json["via"] as? String ?? ""
            let wildcard = json["wildcard"] as? Bool ?? false
            let payloadString = Self.jsonPayloadString(from: json["payload"])
            if wildcard {
                var envelope: [String: Any] = ["event": name]
                envelope["payload"] = json["payload"] ?? NSNull()
                let envelopeJson = (try? JSONSerialization.data(withJSONObject: envelope))
                    .flatMap { String(data: $0, encoding: .utf8) }
                onMain {
                    if let handler = self.handler(for: "\(via)|*") {
                        handler(envelopeJson, NoopResponder.shared)
                    }
                }
            } else if via.isEmpty {
                onMain {
                    if let handler = self.handler(for: "event:on|\(name)") {
                        handler(payloadString, NoopResponder.shared)
                    }
                    if let handler = self.handler(for: "event:once|\(name)") {
                        handler(payloadString, NoopResponder.shared)
                    }
                }
            } else {
                onMain {
                    if let handler = self.handler(for: "\(via)|\(name)") {
                        handler(payloadString, NoopResponder.shared)
                    }
                }
            }
        case "callback":
            let name = json["name"] as? String ?? ""
            let id = json["id"] as? String ?? ""
            let type = json["type"] as? String ?? ""
            let payloadString = Self.jsonPayloadString(from: json["payload"])
            guard let handler = handler(for: "\(type)|\(name)") else {
                reject(id: id, error: "no handler registered for \(name)")
                return
            }
            onMain { handler(payloadString, JsResponder(id: id, bridge: self)) }
        default:
            break
        }
    }

    private func handler(for key: String) -> CallbackHandler? {
        lock.lock()
        defer { lock.unlock() }
        return handlers[key]
    }

    static func jsonPayloadString(from raw: Any?) -> String? {
        guard let raw, !(raw is NSNull) else { return nil }
        if let str = raw as? String { return str }
        if JSONSerialization.isValidJSONObject(raw),
           let data = try? JSONSerialization.data(withJSONObject: raw),
           let str = String(data: data, encoding: .utf8) { return str }
        return nil
    }
}

Step 3: Add the chat screen

Replace YOUR_CLIENT_ID and YOUR_WIDGET_ID with your real values.

import UIKit
import WebKit

final class ChatViewController: UIViewController {
    private var webView: WKWebView!
    private var pleased: PleasedWebViewSetup!

    override func viewDidLoad() {
        super.viewDidLoad()

        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences.allowsContentJavaScript = true
        PleasedWebViewSetup.applyMediaPlaybackPolicy(to: config)

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

        pleased = PleasedWebViewSetup(webView: webView)
        pleased.configure()

        let url = URL(string:
            "https://cdn.pleased.com/widget/native/index.html" +
            "?clientId=YOUR_CLIENT_ID&widgetId=YOUR_WIDGET_ID&platform=ios"
        )!
        webView.load(URLRequest(url: url))
    }
}

Open it from your app:

let chat = ChatViewController()
chat.modalPresentationStyle = .fullScreen
present(chat, animated: true)

Remember:

  • Set your app’s minimum deployment target to iOS 15+ in Xcode.
  • Call applyMediaPlaybackPolicy(to:) before creating the WKWebView.
  • Use platform=ios in the URL (use platform=app on Android).
  • NSCameraUsageDescription is required on a real device if visitors use Take Photo when attaching.

Step 4: Sign in your users and drive the chat

Use this complete chat screen (it replaces Step 3 when you need tokens and events):

import UIKit
import WebKit

final class ChatViewController: UIViewController {
    private var webView: WKWebView!
    private var pleased: PleasedWebViewSetup!
    private var bridge: PleasedBridge!

    override func viewDidLoad() {
        super.viewDidLoad()

        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences.allowsContentJavaScript = true
        PleasedWebViewSetup.applyMediaPlaybackPolicy(to: config)

        bridge = PleasedBridge(configuration: config)

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

        bridge.bind(webView: webView)

        bridge.onLoaderReady = { [weak self, weak bridge] in
            guard let bridge else { return }

            bridge.registerCallback(type: "set:callback", name: "token") { _, respond in
                fetchTokenFromYourBackend { token in
                    let quoted = (try? JSONEncoder().encode(token))
                        .flatMap { String(data: $0, encoding: .utf8) } ?? #""""#
                    respond.resolve(valueJson: quoted)
                }
            }

            bridge.registerCallback(type: "event:on", name: "ready") { [weak bridge] _, _ in
                bridge?.invoke("widget:open", payloadJson: "{}")
            }

            bridge.registerCallback(type: "event:on", name: "close") { [weak self] _, _ in
                self?.dismiss(animated: true)
            }

            bridge.registerCallback(type: "event:on", name: "request_open_settings") { _, _ in
                if let url = URL(string: UIApplication.openSettingsURLString) {
                    UIApplication.shared.open(url)
                }
            }
            bridge.invoke(
                "set:config",
                payloadJson: #"{"capabilities":{"canOpenAppSettings":true}}"#
            )
        }

        pleased = PleasedWebViewSetup(webView: webView)
        pleased.configure()

        let url = URL(string:
            "https://cdn.pleased.com/widget/native/index.html" +
            "?clientId=YOUR_CLIENT_ID&widgetId=YOUR_WIDGET_ID&platform=ios"
        )!
        webView.load(URLRequest(url: url))
    }
}
Important — retain cycles: PleasedBridge keeps every handler you register. Use [weak self] and [weak bridge] on each closure. In onLoaderReady, use guard let bridge else { return } only — not guard let self, or nested handlers can keep the chat screen and WKWebView alive after dismiss.

Keep the close handler so minimising the chat does not leave an empty screen.


Get the key (signed-in visitors)

  1. Settings → Chat Widget Setup in Pleased.
  2. Widget Authentication → Reveal.
Important: Keep the key on your server only. Never embed it in the app.

Create the token on your server

Same as Android: JWE with your public key (RSA-OAEP-256, A128GCM). See the Widget Token guide for a Java example.

Pass the token to the widget

func fetchTokenFromYourBackend(onToken: @escaping (String) -> Void) {
    guard isSignedIn() else {
        onToken("")
        return
    }
    DispatchQueue.global().async {
        let token = (try? String(contentsOf: URL(string: "https://api.example.com/pleased-token")!)) ?? ""
        DispatchQueue.main.async { onToken(token) }
    }
}

If the visitor signs in or out while the chat is open, call bridge.invoke("widget:re_auth").


File attachments

On iOS you do not add file-picker code. WKWebView shows the system picker.

Because the input accepts images, the picker offers Take Photo on a real iPhone. You need NSCameraUsageDescription from Step 1.

Important: If you replace PleasedWebViewSetup as navigationDelegate or uiDelegate, you must keep the same link and navigation behaviour, or attachments and chat links may stop working.

Voice calls

PleasedWebViewSetup answers WebKit’s microphone request (iOS 15+). The visitor sees the system permission dialog.

On iOS, WebKit passes the delegate the top-level page origin (the host page you loaded), not the widget iframe origin as on Android. You normally do not need extra “widget origin” configuration when you load Pleased’s host page from the CDN.

When the microphone is blocked, register request_open_settings and set canOpenAppSettings as in Step 4.

  • With that handler: the visitor may see blocked-microphone copy and an Open settings button (when the widget treats your integration as able to open settings).
  • Without it: the visitor sees “Microphone access is blocked for this site…” with Try again — not an in-app Open settings shortcut. They must open Settings → Your app themselves.

Test voice on a physical iPhone when you can; the Simulator is not enough for real capture.


Verify the installation

  1. Build and run on a real device (at least once for camera + mic).
  2. Chat opens; signed-in greeting shows the user’s name.
  3. Attach a file; try Take Photo (needs camera key).
  4. With an agent online, start a call and allow the microphone.
  5. Minimise the chat; you should return to the previous screen (close handler).

Debug: Safari → Develop → [device] → [your app].


Troubleshooting

  • Chat never appears: check client ID and widget ID; HTTPS if self-hosted.
  • Guests when signed in: token callback / server token / phone format.
  • Bubble over your UI: add platform=ios.
  • Blank after minimise: handle close.
  • No mic prompt: add NSMicrophoneUsageDescription; deployment target iOS 15+; call configure().
  • Crash on Take Photo: add NSCameraUsageDescription.
  • NotAllowedError, no prompt: earlier deny, custom mic delegate, or iframe without allow="microphone".
  • Links/downloads in chat do nothing: do not replace navigation delegate without target="_blank" handling.
  • Blocked mic, no Open settings: add request_open_settings + canOpenAppSettings.
  • No call playback: call applyMediaPlaybackPolicy before creating WKWebView.
  • Chat screen won’t go away / memory: weak captures in bridge handlers (see Step 4).
  • Only Open Request: no agent online.