Native iOS WKWebView Integration Guide
This guide explains how to embed the Talkdesk Chat Widget JS SDK in a native iOS app using WKWebView.
The recommended integration uses a Talkdesk-hosted HTML bridge page. The native app loads that bridge page in a WKWebView, injects the Talkdesk configuration, and receives chat lifecycle events through the iOS JavaScript bridge. You do not need to write or host the bridge page.
Download Sample Code
Download the native iOS example files and bridge HTML used by this guide.
Before You Start: Important Notes
- Set the touchpoint domain in Talkdesk Admin to the host of the bridge page. For the Talkdesk-hosted bridge page that is
talkdeskchatsdk.talkdeskapp.com. See Configure the Touchpoint in Talkdesk Admin. - Destroying the WebView when the user minimizes the chat is fine, and recommended. The conversation is restored from browser storage when chat is launched again, if you keep
WKWebsiteDataStore.default()and turn Clear chat history off for your touchpoint in Talkdesk Admin. See Minimize and Reopen the Chat. - Use the Talkdesk-hosted bridge page. If the bridge page is on a different site than the SDK, the conversation is not kept after the app is killed, see Bridge page and conversation persistence.
- Transcript download is not supported in a native iOS
WKWebView. Disable it for the touchpoint in Talkdesk Admin, see Known Limitation: Transcript Download. - This guide covers iOS. For Android WebView sample and integration guide, see the Android integration guide.
What You Will Build
- Create WKWebView
- Inject config via JavaScript
- Receive SDK events
- Load SDK from CDN
- Call initTalkdeskChat(config)
- Send events to native
The native app is responsible for:
- Creating and showing the
WKWebView - Passing SDK configuration to the bridge page
- Receiving SDK events from JavaScript
- Handling native permissions for attachments
- Opening external links outside the chat WebView
- Cleaning up the WebView when chat closes
The bridge page is responsible for:
- Loading the Talkdesk Chat Widget JS SDK script
- Calling
TalkdeskChatSDK(...) - Calling
webchat.init(...) - Sending events back to Swift
Requirements
- iOS 16 or later
- Swift 5 or later
- A Talkdesk
touchpointId - A Talkdesk region, for example
td-us-1,td-eu-1,td-ca-1, ortd-uk-1 - Access to the Talkdesk-hosted bridge page:
https://talkdeskchatsdk.talkdeskapp.com/v2/ios-playground.html - A touchpoint whose domain is set to the host of the bridge page (see Configure the Touchpoint in Talkdesk Admin)
Always load the bridge page and the SDK over HTTPS, and never from a URL that comes from user input or remote configuration.
Configure the Touchpoint in Talkdesk Admin
Before you test the app, check these settings for the chat touchpoint in Talkdesk Admin (Admin > Channels > Chat > Touchpoints > [your touchpoint]):
- Domain: set it to the host of the bridge page. The chat runs inside the bridge page, so the page host is the domain of your chat. Enter the host only, without
https://and without a path. For the Talkdesk-hosted bridge page used in this guide, entertalkdeskchatsdk.talkdeskapp.com. If you host the bridge page yourself, enter the host of your page. - Transcript download: disabled. It is not supported in a native iOS
WKWebView, see Known Limitation: Transcript Download. - Clear chat history: off. With it off, the chat is kept in local storage, so the conversation is restored when the chat is launched again, even after the WebView was destroyed. With it on, the chat is kept only for the session (session storage) and is lost when the WebView is destroyed. See Minimize and Reopen the Chat.
If the chat does not start after the bridge page loads (the app receives error with Failed to initialize TalkdeskChatSDK), check the touchpoint ID, the region and these settings first. A touchpoint that exists in a different environment than the SDK script is a common cause.
Bridge page and conversation persistence
The chat widget runs in an iframe served from the Talkdesk SDK site (talkdeskchatsdk.talkdeskapp.com) inside the bridge page. Where the bridge page is hosted affects whether a conversation is kept after the app is killed:
- Talkdesk-hosted bridge page (recommended, used by this guide). It is on the same site as the SDK, so the chat state is kept in browser storage and the conversation resumes after the app is killed and relaunched.
- Self-hosted bridge page (your own domain, or a page bundled in the app). The chat iframe is a third-party frame. In our testing on iOS, the conversation resumed while the app stayed alive (for example after closing and reopening the chat), but it was not resumed after the app was killed. Resuming after the app is killed is not guaranteed in this setup. The source of the bridge page is in the ZIP (
bridge/ios-playground.html). If you self-host it, keep it small and trusted.
Why this happens. WebKit documents that storage in a third-party frame is not kept on disk: "Third-party LocalStorage and IndexedDB are partitioned per first-party website and also made ephemeral." It defines ephemeral as storage that "does not persist to disk and goes away with the application." See Tracking Prevention in WebKit on webkit.org. When the bridge page is on a different site than the SDK, the chat iframe is that third-party frame, so its stored conversation is lost when the app is killed. When the bridge page is on the same site, the iframe uses first-party storage, which is kept. The WebKit page does not mention WKWebView by name. The behavior we saw in WKWebView matches it.
Also keep WKWebsiteDataStore.default() (do not use .nonPersistent()). Configuration-only workarounds we tried, such as WKAppBoundDomains, did not change this behavior. This was observed on the iOS 26.4 simulator, so test on your target devices.
Step 1: Add iOS Permissions
If chat attachments are enabled, your app must declare photo, camera, and microphone permissions.
Add these keys to Info.plist:
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to your photo library to upload attachments in chat.</string>
<key>NSCameraUsageDescription</key>
<string>Allow access to your camera to take photos for chat attachments.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Allow access to your microphone for video attachments.</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>tel</string>
<string>mailto</string>
<string>sms</string>
<string>facetime</string>
</array>
If you do not enable attachments, camera and photo permissions are not required.
Step 2: Create the Swift Configuration Model
struct TalkdeskChatConfig {
// Use the Talkdesk-hosted bridge page. It is on the same site as the SDK, so a chat resumes after the app is killed.
// A page on a different site does not. See "Bridge page and conversation persistence".
let bridgeURL: URL
let touchpointId: String
let region: String
let languageCode: String?
let enableEmoji: Bool
// var: the manager turns it off when the user denies camera or photo access.
var enableAttachments: Bool
let enableSoundNotification: Bool
let enableUserInput: Bool
let enableChatHeader: Bool
let enableValidation: Bool
// Optional. The bridge page uses its own defaults when these are left out.
var enableResponsiveLayout = true
var debug = false
// Context for the chat widget, see "Set Context From the Native App".
var context: [String: Any] = [:]
func asDictionary() -> [String: Any] {
var dictionary: [String: Any] = [
"touchpointId": touchpointId,
"region": region,
"enableEmoji": enableEmoji,
"enableAttachments": enableAttachments,
"enableSoundNotification": enableSoundNotification,
"enableUserInput": enableUserInput,
"enableChatHeader": enableChatHeader,
"enableValidation": enableValidation,
"enableResponsiveLayout": enableResponsiveLayout,
"debug": debug
]
if let languageCode, !languageCode.isEmpty {
dictionary["languageCode"] = languageCode
}
if !context.isEmpty {
dictionary["context"] = context
}
return dictionary
}
}
The bridge page validates the configuration it receives, so a wrong value from the app does not break the chat:
touchpointIdandregionare required non-empty strings. If either is missing, the bridge page sends a fatalerrorevent.- On/off options (
enableEmoji,enableAttachments,enableValidation,enableResponsiveLayout,enableSoundNotification,enableUserInput,enableChatHeader) anddebugaccepttrueandfalse. The strings"true"and"false"and the numbers1and0are also accepted. A missing ornullvalue uses the default.debugturns on SDK debug logging and isfalseby default. Leave it off in production builds. - Any other value for an on/off option, or a non-string
languageCode, is ignored and the default is used. The bridge page then sends a non-fatalpageErrorthat lists the option names, never the values. scriptURLis optional and defaults to the Talkdesk SDK. If you pass it, it must be anhttpsaddress. Other schemes, addresses with a user name or password, and plainhttpare refused with a fatalerror.- Defaults when an option is left out: every on/off option is
trueexceptdebug, which isfalse. Set an option explicitly if you need a specific value, for exampleenableValidation. - Options the bridge page does not know are not passed to the SDK.
Example configuration:
let config = TalkdeskChatConfig(
bridgeURL: URL(string: "https://talkdeskchatsdk.talkdeskapp.com/v2/ios-playground.html")!,
touchpointId: "YOUR_TOUCHPOINT_ID",
region: "td-us-1",
languageCode: "en-US",
enableEmoji: true,
enableAttachments: true,
enableSoundNotification: true,
enableUserInput: true,
enableChatHeader: true,
enableValidation: true
)
Step 3: Create the WebView Manager
The manager owns the WKWebView, loads the bridge page, injects the config, receives JavaScript events, and cleans up when chat closes.
import AVFoundation
import Photos
import SwiftUI
import UIKit
import WebKit
struct TalkdeskChatEvent: Identifiable {
let id = UUID()
let type: String
let payload: String?
let timestamp = Date()
}
@MainActor
final class TalkdeskChatWebViewManager: NSObject, ObservableObject {
@Published var webView: WKWebView?
@Published var shouldShowWebView = false
@Published var isLoading = false
@Published var events: [TalkdeskChatEvent] = []
private var pendingConfig: [String: Any]?
// The bridge page we loaded. Only its origin may send events or load in the main frame.
private var bridgeURL: URL?
// True once the bridge page has finished loading, so JavaScript can be sent to it.
private var isBridgeLoaded = false
// Context set by the app. Sent with the config when the bridge page loads.
private var savedContext: [String: Any] = [:]
private let nativeURLSchemes = ["tel", "mailto", "sms", "facetime"]
}
Add launch and cleanup methods:
extension TalkdeskChatWebViewManager {
func launchChat(config: TalkdeskChatConfig) {
isLoading = true
shouldShowWebView = false
guard config.enableAttachments else {
startWebView(config: config)
return
}
// Attachments need camera and photo library access. If the user does not allow it, still start the chat,
// with attachments turned off.
requestAttachmentPermissions { [weak self] granted in
guard let self else { return }
var config = config
if !granted { config.enableAttachments = false }
self.startWebView(config: config)
}
}
func destroyWebView() {
webView?.configuration.userContentController.removeScriptMessageHandler(forName: "sdkEvent")
webView?.navigationDelegate = nil
webView?.uiDelegate = nil
webView = nil
isBridgeLoaded = false
bridgeURL = nil
isLoading = false
shouldShowWebView = false
pendingConfig = nil
}
}
Add WebView creation:
private extension TalkdeskChatWebViewManager {
func startWebView(config: TalkdeskChatConfig) {
pendingConfig = config.asDictionary()
let webViewConfig = WKWebViewConfiguration()
// Persistent store: keeps chat state across launches. Do not use .nonPersistent().
// The bridge page must also be on the same site as the SDK, see "Bridge page and conversation persistence".
webViewConfig.websiteDataStore = .default()
let contentController = WKUserContentController()
contentController.add(self, name: "sdkEvent")
webViewConfig.userContentController = contentController
let webView = WKWebView(frame: .zero, configuration: webViewConfig)
webView.navigationDelegate = self
webView.uiDelegate = self
webView.scrollView.bounces = false
webView.scrollView.contentInsetAdjustmentBehavior = .automatic
self.webView = webView
bridgeURL = config.bridgeURL
webView.load(URLRequest(url: config.bridgeURL))
}
}
Step 4: Inject SDK Config After the Bridge Page Loads
extension TalkdeskChatWebViewManager: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
isBridgeLoaded = true
// Context set before the page loaded goes with the config. The bridge page applies it before the SDK starts.
guard var config = pendingConfig else { return }
if !savedContext.isEmpty {
var context = config["context"] as? [String: Any] ?? [:]
context.merge(savedContext) { _, new in new }
config["context"] = context
}
guard let jsonData = try? JSONSerialization.data(withJSONObject: config),
let jsonString = String(data: jsonData, encoding: .utf8) else {
handleError("Failed to serialize Talkdesk Chat config")
return
}
webView.evaluateJavaScript("window.initTalkdeskChat(\(jsonString))") { [weak self] _, error in
if let error {
Task { @MainActor in
self?.handleError("Failed to inject Talkdesk Chat config: \(error.localizedDescription)")
}
}
}
self.pendingConfig = nil
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
if isRecoverableNavigationInterruption(error) { return }
handleError("Failed to load Talkdesk Chat: \(error.localizedDescription)")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
if isRecoverableNavigationInterruption(error) { return }
handleError("Failed to start Talkdesk Chat load: \(error.localizedDescription)")
}
}
Some WebView navigation interruptions are expected, especially when links or downloads leave the WebView. Do not destroy chat for these recoverable cases:
private extension TalkdeskChatWebViewManager {
func isRecoverableNavigationInterruption(_ error: Error) -> Bool {
let nsError = error as NSError
let frameLoadInterruptedByPolicyChange = 102
return (nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled) ||
(nsError.domain == WKError.errorDomain && nsError.code == frameLoadInterruptedByPolicyChange)
}
}
Step 5: Receive SDK Events From JavaScript
Add these helpers to compare an origin with the bridge page you loaded. They are used by the message handler below and by the navigation check in Step 6:
extension TalkdeskChatWebViewManager {
// An origin is scheme + host + port. Compare with the bridge page we loaded, never with what a page claims.
func matchesBridgeOrigin(scheme: String, host: String, port: Int?) -> Bool {
guard let bridge = bridgeURL,
let bridgeScheme = bridge.scheme?.lowercased(),
let bridgeHost = bridge.host?.lowercased() else { return false }
func effectivePort(_ scheme: String, _ port: Int?) -> Int {
if let port, port != 0 { return port }
return scheme == "https" ? 443 : 80
}
let scheme = scheme.lowercased()
return scheme == bridgeScheme
&& host.lowercased() == bridgeHost
&& effectivePort(scheme, port) == effectivePort(bridgeScheme, bridge.port)
}
func isBridgeURL(_ url: URL) -> Bool {
guard let scheme = url.scheme, let host = url.host else { return false }
return matchesBridgeOrigin(scheme: scheme, host: host, port: url.port)
}
func isBridgeOrigin(_ origin: WKSecurityOrigin) -> Bool {
matchesBridgeOrigin(scheme: origin.protocol, host: origin.host, port: origin.port)
}
}
extension TalkdeskChatWebViewManager: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
// Only trust the bridge page. A script message handler is reachable from every frame, and a page that
// navigated the main frame elsewhere would still pass isMainFrame, so the origin is checked too.
guard message.frameInfo.isMainFrame,
isBridgeOrigin(message.frameInfo.securityOrigin),
let body = message.body as? [String: Any],
let rawType = body["type"] as? String else {
return
}
let type = rawType.trimmingCharacters(in: .whitespacesAndNewlines)
guard !type.isEmpty else { return }
let payload = (body["payload"] as? [String: Any]).flatMap { payload in
try? String(data: JSONSerialization.data(withJSONObject: payload), encoding: .utf8)
}
events.append(TalkdeskChatEvent(type: type, payload: payload))
switch type {
case "sdkReady":
isLoading = false
shouldShowWebView = true
webView?.evaluateJavaScript("window.openTalkdeskChat()", completionHandler: nil)
case "onCloseWebchat", "error":
// Closing the chat or an error: clean up. The conversation is restored from browser storage next time.
destroyWebView()
default:
break
}
}
}
The bridge page sends error only for fatal problems: an invalid configuration, or the SDK failing to load or initialize. Tear the WebView down or reload it on error. Non-fatal runtime errors in the page are sent as pageError. Treat pageError as informational and do not close the chat for it. Ignore event types your app does not handle.
Do not show the visible chat container before sdkReady. It is fine to mount the WKWebView hidden so the bridge page can load, but the customer should only see the chat WebView after the SDK is initialized.
Minimize and Reopen the Chat
When the user minimizes or closes the chat, the bridge page sends onCloseWebchat. We recommend destroying the WebView at that point, as in Step 5, and creating a new one the next time chat is launched. The conversation is not kept in the WebView itself: the chat restores it from browser storage, so the user continues the same conversation.
For this to work:
- Keep
WKWebsiteDataStore.default()(a persistent store). Do not use.nonPersistent(). - Turn Clear chat history off for the touchpoint in Talkdesk Admin (Configure the Touchpoint in Talkdesk Admin). Off keeps the chat in local storage. With it on, the chat state lives in
sessionStorage, which is lost when the WebView is destroyed, so the conversation would start again. - Resuming after the app is killed also needs the Talkdesk-hosted bridge page, see Bridge page and conversation persistence.
Destroying the WebView also frees its memory while the chat is closed. If you prefer to keep it, or Clear chat history is on for your touchpoint, you can hide the WebView instead of destroying it and show it again on the next launch, calling window.openTalkdeskChat() and not loading the bridge page again. The Talkdesk sample app does this by default, and destroys the WebView instead when its Destroy WebView on minimize (test) switch is on. Whichever you choose, drop the WebView after an error event.
iOS can also end the WebView's web content process, for example under memory pressure. The page is then blank and cannot recover. Add this method to the WKNavigationDelegate extension from Step 4 so the next launch creates a new WebView:
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
destroyWebView()
}
Set Context From the Native App
Your app can pass context (key and value pairs such as a customer id or the current app screen) to the chat widget. Context values must be strings. Numbers and booleans are converted to strings, null is skipped, and objects and arrays are ignored.
To set context before the chat starts, pass it in the configuration, under context. It goes to the bridge page with the rest of the configuration:
let config = TalkdeskChatConfig(
bridgeURL: URL(string: "https://talkdeskchatsdk.talkdeskapp.com/v2/ios-playground.html")!,
touchpointId: "YOUR_TOUCHPOINT_ID",
region: "td-us-1",
languageCode: nil,
enableEmoji: true,
enableAttachments: true,
enableSoundNotification: true,
enableUserInput: true,
enableChatHeader: true,
enableValidation: true,
context: ["customerId": "12345", "screen": "accounts"]
)
To set or update it at any time, call setContext. Calls are merged with earlier context. The manager keeps the context, so it is sent again every time a new WebView is created (for example after the user minimizes the chat and the WebView is destroyed). A call made before the bridge page has loaded, or before the chat is launched, is sent with the configuration. Call clearContext() to forget it:
extension TalkdeskChatWebViewManager {
func setContext(_ context: [String: Any]) {
// Build the JavaScript argument with JSONSerialization.
// Never concatenate context values into the script string yourself.
guard JSONSerialization.isValidJSONObject(context),
let data = try? JSONSerialization.data(withJSONObject: context),
let json = String(data: data, encoding: .utf8) else { return }
savedContext.merge(context) { _, new in new }
// The bridge page cannot receive JavaScript before it has loaded. Then the saved context is sent
// with the configuration in Step 4.
guard isBridgeLoaded else { return }
webView?.evaluateJavaScript("window.setTalkdeskChatContext(\(json))", completionHandler: nil)
}
func clearContext() {
savedContext = [:]
}
}
The bridge page sends contextUpdated with the key names once the context is applied. Values are never sent back to the app. Context that cannot be used is reported as a non-fatal pageError and never closes the chat.
Context can contain personal data. Send only what the chat flow needs, and do not log context values in your app.
If you maintain your own bridge page, expose a function that calls webchat.setContextParam(context) with string values, and keep calls made before the SDK is created until it is.
Step 6: Open External Links Outside the Chat WebView
User-facing links should leave the chat WebView and open through iOS.
This includes:
- Normal
https://links clicked by the user target="_blank"links- JavaScript
window.open(...) tel:,mailto:,sms:, andfacetime:links
extension TalkdeskChatWebViewManager: WKUIDelegate {
func webView(
_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures
) -> WKWebView? {
if let url = navigationAction.request.url {
_ = openExternallyIfNeeded(url)
}
return nil
}
}
extension TalkdeskChatWebViewManager {
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
if let url = navigationAction.request.url,
(nativeURLSchemes.contains(url.scheme?.lowercased() ?? "") ||
navigationAction.navigationType == .linkActivated),
openExternallyIfNeeded(url) {
decisionHandler(.cancel)
return
}
// Only the bridge page may load in the main frame. Anything else, such as a redirect or a script that sets
// the location, goes to the system browser and is blocked here, so no other page gets the "sdkEvent" handler.
if navigationAction.targetFrame?.isMainFrame == true,
let url = navigationAction.request.url,
let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https",
!isBridgeURL(url) {
_ = openExternallyIfNeeded(url)
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
private func openExternallyIfNeeded(_ url: URL) -> Bool {
guard let scheme = url.scheme?.lowercased() else { return false }
if nativeURLSchemes.contains(scheme) || scheme == "http" || scheme == "https" {
UIApplication.shared.open(url)
return true
}
return false
}
}
Step 7: Request Attachment Permissions
Only request these permissions if attachments are enabled. If the user does not allow them, do not block the chat: start it with enableAttachments set to false (see launchChat in Step 3). If access was denied earlier, iOS does not show the prompt again, so skip the request and start the chat with attachments off.
private extension TalkdeskChatWebViewManager {
func requestAttachmentPermissions(completion: @escaping (Bool) -> Void) {
let photoStatus = PHPhotoLibrary.authorizationStatus(for: .readWrite)
let cameraStatus = AVCaptureDevice.authorizationStatus(for: .video)
if photoStatus == .denied || photoStatus == .restricted ||
cameraStatus == .denied || cameraStatus == .restricted {
completion(false)
return
}
PHPhotoLibrary.requestAuthorization(for: .readWrite) { photoStatus in
AVCaptureDevice.requestAccess(for: .video) { cameraGranted in
let photoGranted = photoStatus == .authorized || photoStatus == .limited
DispatchQueue.main.async {
completion(photoGranted && cameraGranted)
}
}
}
}
}
Step 8: Add Error Handling
private extension TalkdeskChatWebViewManager {
func handleError(_ message: String) {
events.append(TalkdeskChatEvent(type: "error", payload: "{\"message\":\"\(message)\"}"))
destroyWebView()
}
}
For production apps, show a friendly native error message, for example:
Chat is currently unavailable. Please try again later.
Avoid showing raw technical errors directly to end users.
Step 9: Create the SwiftUI WebView Wrapper
struct TalkdeskChatWebView: UIViewRepresentable {
let webView: WKWebView
func makeUIView(context: Context) -> WKWebView {
webView.scrollView.bounces = false
webView.scrollView.contentInsetAdjustmentBehavior = .automatic
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.scrollView.verticalScrollIndicatorInsets = uiView.safeAreaInsets
}
}
Step 10: Display the Chat WebView Safely
Use a native container around the WebView.
The container background may cover the full screen, including the bottom safe-area area. The WebView itself should still respect the safe area so the chat input is not hidden by the Home Indicator.
struct ContentView: View {
@StateObject private var manager = TalkdeskChatWebViewManager()
private let chatConfig = TalkdeskChatConfig(
bridgeURL: URL(string: "https://talkdeskchatsdk.talkdeskapp.com/v2/ios-playground.html")!,
touchpointId: "YOUR_TOUCHPOINT_ID",
region: "td-us-1",
languageCode: "en-US",
enableEmoji: true,
enableAttachments: true,
enableSoundNotification: true,
enableUserInput: true,
enableChatHeader: true,
enableValidation: true
)
var body: some View {
ZStack {
mainScreen
.zIndex(manager.shouldShowWebView ? 0 : 1)
if let webView = manager.webView {
ZStack {
Color.white
.ignoresSafeArea()
.opacity(manager.shouldShowWebView ? 1 : 0)
TalkdeskChatWebView(webView: webView)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.white)
.opacity(manager.shouldShowWebView ? 1 : 0)
}
.zIndex(manager.shouldShowWebView ? 1 : 0)
.allowsHitTesting(manager.shouldShowWebView)
}
}
}
private var mainScreen: some View {
VStack(spacing: 16) {
Text("Need help?")
.font(.title)
Button {
manager.launchChat(config: chatConfig)
} label: {
if manager.isLoading {
ProgressView()
} else {
Text("Start Chat")
}
}
.disabled(manager.isLoading)
}
.padding()
}
}
The sample app starts the chat from a floating trigger button instead of the plain button above. See Optional: Floating Chat Trigger.
Why this layout matters:
- The WebView can be mounted before
sdkReady, but it stays invisible. - The customer only sees chat after
sdkReady. - The full-screen background prevents the underlying native screen from showing behind the keyboard.
- The WebView itself does not ignore the bottom safe area, so the chat input stays above the Home Indicator.
Optional: Floating Chat Trigger
The sample app starts the chat from a floating button fixed to a corner of the screen, like the launcher of the web chat widget. It is optional: you can use it, or start the chat from any control in your app.
The button is a ready-made SwiftUI view, ChatTriggerButton. Its code and its default icon are in the TDChatWidgetTrigger folder of the download:
TDChatWidgetTrigger/
ChatTriggerButton.swift
TDChatWidgetTrigger.xcassets/
ChatTriggerIcon.imageset/ (default icon, PNG at 1x, 2x and 3x)
Add it to your project
Drag the whole TDChatWidgetTrigger folder into your Xcode project and make sure it is added to your app target. Add the folder as a group, not as a folder reference, so the Swift file is compiled and the icon is part of the app. If the icon is missing, the button shows a system symbol instead.
Use it
Put the button in an .overlay (or a ZStack) on a view that fills the screen. It places itself in the corner you choose and stays clear of the safe area. Replace the "Start Chat" button of Step 10 with it:
private var mainScreen: some View {
Text("Need help?")
.font(.title)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.overlay {
ChatTriggerButton(
style: ChatTriggerStyle(),
isLoading: manager.isLoading,
isEnabled: true
) {
manager.launchChat(config: chatConfig)
}
}
}
isLoading shows a spinner and ignores taps while the chat starts. isEnabled dims the button and ignores taps, for example while a required setting is missing.
Customize it
Everything is set through ChatTriggerStyle. Every value has a default, so set only what you want to change:
ChatTriggerStyle(
position: .bottomLeading,
isDraggable: true,
width: 72,
height: 72,
backgroundColor: .indigo
)
Swift needs the options in the order of the table below, so keep that order when you set several.
| Option | Default | What it does |
|---|---|---|
position | .bottomTrailing | Corner of the screen: .bottomTrailing or .bottomLeading |
horizontalInset, verticalInset | 20 | Distance from the screen edge and the safe area where the button rests, in points. It does not limit dragging |
isDraggable | false | Lets the user drag the button anywhere on screen |
width, height | 64, 64 | Size in points, not pixels. With a title, width is a minimum and the button grows with the text |
shape | .circle | .circle or .roundedSquare(cornerRadius:). A circle with different width and height becomes a capsule |
backgroundColor | .accentColor | Your app's accent color. iOS system blue unless the app sets AccentColor |
foregroundColor | white | Color of the spinner, the title and the default icon. It does not change an icon loaded from iconURL |
iconURL | nil | https address of a PNG or JPEG image that replaces the default icon |
iconAssetName | "ChatTriggerIcon" | Name of an image in your asset catalog used as the default icon. It is drawn as a template, so foregroundColor colors it |
iconSystemName | chat bubbles symbol | System symbol used when iconAssetName is not in the app |
iconSize | 28 | Size of the icon in points |
title | none | Text next to the icon. The button becomes a pill |
shadowColor, shadowRadius | black 25%, 6 | Shadow under the button |
disabledOpacity | 0.5 | Opacity while isEnabled is false |
pressedScale | 0.92 | Scale while the finger is down. Use 1 for no effect |
hapticFeedback | true | Light haptic tap when the button is tapped |
accessibilityLabel | "Launch Chat" | Read by VoiceOver. The title is used instead when there is one |
Good to know
- Icon. The default icon is bundled in the app, so it needs no network. To use your own, add an image to your asset catalog and set
iconAssetName, or seticonURL. A customiconURLmust behttps, a PNG or JPEG, at most 512 KB. SVG is not supported there: add an SVG to your asset catalog instead. If the image cannot be loaded, the default icon is shown. - Dragging. With
isDraggableon, the button can be dragged anywhere in the safe area, right up to the edges: the insets only set where it rests, they do not limit the drag. It never leaves the safe area. A touch that moves less than a few points counts as a tap and starts the chat. The new position is kept while the screen is shown and is not saved when the app restarts. VoiceOver cannot drag, so it uses the normal tap action. - Chat on top. The chat covers the whole screen when it opens, so the button is hidden behind it until the chat is closed.
Step 11: Test the Integration
Test these cases before shipping:
- Chat opens after tapping the native chat button.
- If you use the floating trigger, it stays fixed while the screen scrolls, and can be dragged when
isDraggableis on. - Chat does not visibly appear until
sdkReadyis received. - Chat input is not hidden by the iPhone Home Indicator.
- Keyboard open and close does not reveal the native screen behind the WebView.
- Closing chat removes the WebView and returns to the native screen.
- Attachment upload asks for camera/photo permissions only when attachments are enabled.
- Denied camera or photo permissions still start the chat, with attachments turned off.
https://links open in Safari or the user's default browser.tel:,mailto:,sms:, andfacetime:links open the correct iOS app.target="_blank"links andwindow.open(...)do not fail silently.- Poor network conditions show a friendly error or loading state.
Known Limitation: Transcript Download
If the web SDK generates transcript downloads using a temporary blob: URL and an <a download> click, native iOS WKWebView cannot reliably save that blob-backed file.
Transcript download is currently supported for web browser integrations, but not for native iOS WKWebView integrations.
For iOS app integrations, disable transcript download for the chat touchpoint in Talkdesk Admin:
Admin > Channels > Chat > Touchpoints > [your touchpoint] > disable transcript download
Treat transcript download as unsupported in native iOS unless you implement and validate a separate native download flow.
The app should ignore recoverable WebView navigation interruptions so chat stays open, but it should not tell users that transcript download is supported unless the native app handles it explicitly.
Common Issues
| Issue | Likely Cause | Fix |
|---|---|---|
| Chat never appears | sdkReady was not received | Check bridge page URL, SDK script URL, touchpointId, and region |
Chat does not start, error with Failed to initialize TalkdeskChatSDK | Wrong touchpointId or region, a touchpoint from a different environment than the SDK script, or touchpoint settings that do not match | Check the touchpoint ID and region, and the settings in Configure the Touchpoint in Talkdesk Admin |
| Conversation is lost after the app is killed | Bridge page is on a different site than the SDK, so the chat iframe is a third-party frame | Use the Talkdesk-hosted bridge page, and keep WKWebsiteDataStore.default(). See Bridge page and conversation persistence |
| Native screen shows behind keyboard | Container background does not cover the full screen | Add a native container background with .ignoresSafeArea() |
| Chat input is hidden by Home Indicator | WebView ignores bottom safe area | Do not apply .ignoresSafeArea(edges: .bottom) to the WebView itself |
| External links do nothing | WKUIDelegate.createWebViewWith is missing | Implement createWebViewWith and open URLs through UIApplication.shared.open |
| Camera/photo upload fails | Missing Info.plist permissions | Add photo, camera, and microphone permission strings |
| App crashes when selecting attachment | Permission keys are missing | Add the required Info.plist keys before enabling attachments |
| Chat closes after a link/download navigation | Recoverable navigation error was treated as fatal | Ignore NSURLErrorCancelled and WKError code 102 |
Production Checklist
- Load the Talkdesk-hosted bridge page over HTTPS. Do not self-host it if conversations must resume after the app is killed.
- Use the correct production
touchpointIdand region. - If you self-host the bridge page, keep it small and trusted.
- Do not expose secrets in the bridge page or SDK config.
- Register and remove the
sdkEventmessage handler correctly. - Show chat only after
sdkReady. - Set the touchpoint domain in Talkdesk Admin to the host of the bridge page.
- Disable transcript download for iOS app chat touchpoints in Talkdesk Admin.
- Destroy the WebView on
onCloseWebchatand on unrecoverable errors, keepWKWebsiteDataStore.default(), and turn Clear chat history off for the touchpoint so the conversation is restored when chat is launched again. - Test on a real iPhone with a Home Indicator.
- Test with keyboard, attachments, external links, and poor network conditions.