iOS 向けヘッドレス モバイル SDK: スマート アクション、添付ファイル、回避

このドキュメントでは、Android アプリケーションで Headless Mobile SDK を統合してカスタマイズする方法について説明します。サポート セッションにリッチな構造化情報を追加するすべての機能(コンテキスト取得のためのセッション前のスマート アクション、エージェントによってトリガーされるセッション内のスマート アクション(LocalAuthentication を使用した生体認証を含む)、ウェブフォームとカスタム フォーム、お客様とエージェントが開始した添付ファイル、営業時間外や容量超過のシナリオでの回避処理)が含まれます。

スマート アクションと添付ファイルを構成する

スマート アクションを使用すると、エージェントと消費者は、写真、動画、テキスト スニペット、生体認証(Face ID、Touch ID)などのリッチな構造化情報を交換できます。

ヘッドレス アーキテクチャでは、SDK はセキュアなトランスポート レイヤとしてのみ機能します。アクションが必要な場合やリクエストされた場合を通知し、データを Google Cloud プロジェクト プラットフォームに安全に転送します。ユーザー インターフェースはアプリが所有しているため、カメラ画面、フォト ピッカー、テキスト ボックスの描画、Apple の Face ID プロンプトのトリガーは、アプリが完全に担当します。

セッション前のスマート アクション

セッション前の操作では、ユーザーがキューに参加する前にコンテキスト(口座番号や破損した製品の動画など)を収集するため、エージェントの処理時間を大幅に短縮できます。

SDK が提供するもの: 特定のキューのルールと要件(参加前に生体認証、写真のアップロード、テキスト入力が任意か必須かなど)。

構築するもの: ユーザーがキューをタップしてから待機室に入るまでの間に表示されるセッション前の UI 画面(カメラ、テキスト入力、Face ID プロンプト)と、セッションが接続されるまでメディアを安全に保持するディスク キャッシュ ロジック。

実装例

このコードは、選択したキューにセッション前の要件があるかどうかを確認するために、SDK の構成をチェックします。このサンプルでは、動画をメモリに保持するのではなく、ディスク上のファイル URL 参照を保持することで、動画の要件を処理する方法を示します。

// 1. Check requirements and collect data BEFORE joining the queue
func checkPreSessionRequirements(for menu: QueueMenu) {
    guard let smartActions = menu.settings else {
        startChat(for: menu)
        return
    }

    // Example: handle a video requirement
    presentVideoPicker { (localFileURL) in
        // IMPORTANT: localFileURL should point to NSTemporaryDirectory()
        MySessionStateManager.shared.pendingPreSessionVideo = localFileURL
        self.startChat(for: menu)
    }
}

// 2. Upload and clean up AFTER the session officially connects
func handleSessionConnected() {
    guard let pendingVideoURL = MySessionStateManager.shared.pendingPreSessionVideo else { return }

    // Upload using the standard in-session pipeline
    // then clean up the temporary file
    try? FileManager.default.removeItem(at: pendingVideoURL)
    MySessionStateManager.shared.pendingPreSessionVideo = nil
}

プリセッション SmartAction の構成を読み取っています

SDK は、2 つの補完的なパスを介してセッション前のスマート アクション構成を公開します。両方を確認して、特定のキューとチャネルでセッション前のキャプチャが必要かどうかを判断します。

パス A - キューレベル(QueueMenu.settings[].sdk.preSessionSmartAction):

public struct QueueMenuSetting: Decodable {
    public let sdk: QueueMenuSDKSetting?
    // ... other fields ...
}

public struct QueueMenuSDKSetting: Decodable {
    public let preSessionSmartAction: Bool?
    // ... other fields ...
}

// Usage - "does any queue-level setting require a pre-session smart action?"
func queueRequiresPreSession(_ menu: QueueMenu) -> Bool {
    return menu.settings?.contains { $0.sdk?.preSessionSmartAction == true } ?? false
}

パス B - チャンネル レベル(VoiceCallChannel.preSessionSmartAction):

// Usage - "does the voice channel specifically require pre-session capture?"
let requiresPreSessionOnVoice =
    menu.channels?.voiceCall?.preSessionSmartAction == true

パス A を使用して、ユーザーがチャンネルを選択する前にセッション前のゲートを表示するかどうかを決定します。チャネルが選択された後のチャネル固有の調整(たとえば、インスタント音声通話の前にのみプロンプトを表示するなど)には、パス B を使用します。

セッション内のスマート アクション(エージェントが開始)

チャットまたは音声通話中に、エージェントはダッシュボードのボタンを選択して、ユーザーにデータの提供をリクエストできます(「身分証明書の写真を送信してください」や「Face ID で認証してください」など)。

SDK が提供するもの: エージェントが特定タイプのスマート アクションをリクエストしたことをアプリに通知するリアルタイム イベント。

作成するもの: リクエストをユーザーに通知し、適切な組み込みツール(カメラ、フォト ライブラリ、テキスト フィールド、Face ID)を起動して、結果を SDK に渡す、チャット内または通話内のアラート。

実装例

ここでは、アプリが SDK イベントをリッスンします。エージェント リクエストを検出すると、アラートが表示され、適切な iOS ツールが開きます。

// Listen for Smart Action requests from the active SDK session.
//
// `SmartActionType` exposes the following cases: `.photo`, `.video`,
// `.screenshot`, `.text`, `.verification`, `.screenShare`, `.unknown`.
// Use `.verification` (not `.biometric`) for Face ID / Touch ID flows -
// there is no `.biometric` case on the enum.
func handleSmartActionRequest(_ request: SmartActionRequest) {
    switch request.type {
    case .photo:
        promptUserForPhoto(message: "The agent requested a photo.") { capturedImage in
            // Send the image back to the agent using the SDK
            self.sendAttachment(image: capturedImage)
        }

    case .video:
        // Agent-requested video capture. Reuse the same disk-caching pattern
        // recommended for pre-session media - keep the recording on disk and
        // pass the file URL to the SDK rather than holding the raw `Data` in
        // memory.
        promptUserForVideo(message: "The agent requested a video.") { capturedVideoURL in
            self.sendAttachment(videoURL: capturedVideoURL)
        }

    case .screenshot:
        // The SDK exposes `.screenshot` as a distinct request type - the user
        // captures (or selects) a single still image of the current screen.
        // This is **not** the same as the following `.screenShare` case, which starts a
        // live co-browse session.
        promptUserForScreenshot(message: "The agent requested a screenshot.") { capturedImage in
            self.sendAttachment(image: capturedImage)
        }

    case .verification:
        // Use Face ID / Touch ID using LocalAuthentication. The SDK exposes
        // this case as `.verification`; there is no `.biometric` case on
        // `SmartActionType`.
        performAppleBiometricAuth { success in
            self.sendBiometricResult(success: success)
        }

    case .text:
        presentTextInputPrompt(message: "The agent requested text input.") { text in
            self.sendSmartActionText(text)
        }

    case .screenShare:
        // Hand off to the full screen share flow (see Headless Mobile SDK for iOS: Voice, Screen Share, Scheduled Call, and Email).
        // Don't confuse this with `.screenshot` described earlier - `.screenShare` starts a
        // live co-browse session using `CCAIScreenShare`, while `.screenshot`
        // captures a single still frame.
        startScreenShareFlow()

    case .unknown:
        // Future-proof: a smart action type the SDK doesn't recognize.
        // Log and continue - don't block the user.
        print("CCAI: received unknown smart action type")

    @unknown default:
        // Defensive: handle any cases added to `SmartActionType` in future
        // SDK releases.
        break
    }
}

スマート アクションの通知とトラッキング

smartActionService を使用して、ユーザーがスマート アクションを進めるにつれて、スマート アクションを認識して更新します。

let router = CommunicationRouter(id: chatId, type: .chat)

// Notify the server that a smart action has been received
do {
    try await CCAI.shared.smartActionService?.notifySmartActionReceived(
        router: router,
        smartActionId: smartActionId
    )
    print("Smart action notification sent successfully")
} catch {
    print("Failed to notify smart action: \(error)")
}

// Update the smart action status as the user completes it
do {
    try await CCAI.shared.smartActionService?.updateSmartActionStatus(
        router: router,
        smartActionId: smartActionId,
        status: .finished
    )
    print("Smart action status updated successfully")
} catch {
    print("Failed to update smart action status: \(error)")
}

アクションでテキスト入力が求められる場合は、UI でテキストを収集し、スマート アクション サービスを介して送信してから、アクションを完了済みとしてマークします。

ウェブフォーム

SDK が提供するもの: チャット セッション中にエージェントによってトリガーされたウェブフォームを取得、表示、検証するための API。

構築するもの: ウェブフォームのレンダリング UI と、ユーザーの回答をパッケージ化する送信フロー。

実装例

このコードは、スマート アクション ID と外部フォーム ID でウェブフォームを取得し、送信前にレスポンスを検証します。

// Fetch a web form - WebFormRequest has no `signature` parameter on iOS
let webFormRequest = WebFormRequest(
    smartActionId: 123,
    externalFormId: "form123"
)

do {
    let webFormResponse = try await CCAI.shared.chatService?.fetchWebForm(webFormRequest)
    if let response = webFormResponse {
        print("Web form received: \(response)")
    }
} catch {
    print("Failed to fetch web form: \(error)")
}

// Validate a web form response
do {
    let isValid = try await CCAI.shared.chatService?.validateWebForm(webFormResponse)
    if isValid == true {
        print("Web form is valid")
    } else {
        print("Web form validation failed")
    }
} catch {
    print("Failed to validate web form: \(error)")
}

WebFormResponse、FormPayload、WebFormData 構造体の定義の完全版については、Headless Mobile SDK - iOS API リファレンスをご覧ください。

カスタム フォーム

SDK が提供するもの: 構成可能なフォーム定義(複数の質問タイプを含む)を取得し、ユーザーの回答を送信するための API。

構築するもの: 各質問タイプ(テキスト フィールドやプルダウンなど)をレンダリングし、入力を検証して、送信用の回答を収集する動的フォーム UI。

実装例

このコードは、カスタム フォームの質問の定義を取得し、ユーザーの回答をパッケージ化して送信します。

// Retrieve custom form details
do {
    let form = CustomForm(
        id: 123,
        name: nil,
        title: nil,
        subtitle: nil,
        smartActionId: nil,
        image: nil,
        header: nil,
        footer: nil
    )
    let formDetails = try await CCAI.shared.chatService?.getCustomFormDetails(form)
    if let details = formDetails {
        print("Form Title: \(details.title ?? "No title")")
        print("Questions: \(details.questions.count)")
    }
} catch {
    print("Failed to get custom form details: \(error)")
}

// Submit a custom form
let request = SubmitCustomFormRequest(
    smartActionId: 123,
    formResponse: [
        SubmitCustomFormRequest.Answer(questionId: 1, value: "John Doe"),
        SubmitCustomFormRequest.Answer(questionId: 2, value: "john@example.com")
    ]
)

do {
    try await CCAI.shared.chatService?.submitCustomForm(request: request)
    print("Form submitted successfully")
} catch {
    print("Failed to submit form: \(error)")
}

CustomFormDetailsResponse、CustomFormQuestion、CustomFormQuestionOption、CustomFormQuestionType 列挙型の定義については、Headless Mobile SDK - iOS API リファレンスをご覧ください。

お客様が開始した添付ファイル(チャット)

エージェントからの質問を待つ必要はなく、チャット中に画像や動画を積極的に送信できます。SDK は厳格なファイルサイズ制限を適用し、送信前に自動的に圧縮を試みます。

添付ファイルのサイズ制限

  • 画像: ≤ 2 MB

  • 動画: ≤ 20 MB

SDK の機能: ネットワーク送信を処理し、 Google Cloud プロジェクトの制限を満たすようにファイルを自動的に圧縮する安全なアップロード パイプライン。

構築するもの: チャット UI のクリップ / 添付ファイル ボタン、写真 / 動画選択ツール、アップロード状態(読み込み中、送信済み、失敗)を示す視覚的なチャット バブル。

実装例

ユーザーがカメラロールから写真または動画を選択したら、Data(画像の場合)に変換するか、ローカル ファイルの URL(動画の場合)を取得し、すべての送信メッセージに使用される同じ sendMessage API を使用して SDK に渡します(Headless Mobile SDK for iOS: キュー、チャンネル、チャットのメッセージの送信セクションを参照)。圧縮とアップロードは SDK が処理します。

import PhotosUI

// Called when the user picks an image from their photo library
func userDidSelectImage(_ image: UIImage) {
    guard let imageData = image.jpegData(compressionQuality: 0.8) else { return }

    // Show a loading bubble in your custom chat UI
    let messageBubble = myChatUI.addLoadingImageBubble()

    Task {
        do {
            // Wrap the raw data in an UploadableImage
            let uploadableImage = UploadableImage(data: imageData, mimeType: "image/jpeg")

            // Pass to the SDK - compression and upload are handled automatically
            try await CCAI.shared.chatService?.sendMessage(
                .images(images: [uploadableImage], smartAction: nil)
            )
            messageBubble.markAsSent()
        } catch {
            // The SDK returns an error if the file exceeds limits even after compression
            messageBubble.showError("Failed to send: \(error.localizedDescription)")
        }
    }
}

// Called when the user picks a video from their photo library
func userDidSelectVideo(at localURL: URL) {
    let messageBubble = myChatUI.addLoadingVideoBubble()

    Task {
        do {
            let uploadableVideo = UploadableVideo(url: localURL, mimeType: "video/mp4")
            try await CCAI.shared.chatService?.sendMessage(
                .videos(videos: [uploadableVideo], smartAction: nil)
            )
            messageBubble.markAsSent()
        } catch {
            messageBubble.showError("Failed to send: \(error.localizedDescription)")
        }
    }
}

エージェントが開始した添付ファイル(チャット)

エージェントは、画像、動画、音声クリップ、ドキュメント(PDF、CSV など)などのファイルをユーザーに送信できます。

サポートされているファイル形式

Google Cloud プロジェクト プラットフォームでは、4 つのカテゴリにわたる 19 種類のファイル形式がサポートされています。カスタム UI は、各カテゴリ(画像プレビュー、動画プレーヤー、音声プレーヤー、ドキュメントのダウンロード)を適切に処理する必要があります。

カテゴリ サポートされる形式
画像 JPEG、PNG、GIF、WebP。
動画 MP4、MOV、AVI、WMV、WebM。
音声 MP3、WAV、M4A、WEBA。
ドキュメント PDF、DOC、XLS、PPT、CSV、TXT。

SDK が提供するもの: 受信チャット メッセージのペイロード(messagesReceived Combine パブリッシャーを使用して配信 - Headless Mobile SDK for iOS: セッション後のトピックと高度なトピックのCombine を使用したリアクティブ パターンのセクションを参照)。これには添付ファイルのメタデータが含まれます。チャット サービスは、エージェントが送信したメディアを安全に取得するための downloadMedia も提供します)。

作成するもの: チャット フィードでこれらの添付ファイルをレンダリングする UI。アプリは、画像プレビュー、動画サムネイル、音声再生コントロール、ドキュメント ダウンロード ボタンを表示するかどうかを決定します。

実装例

messagesReceived を使用して、受信メッセージを購読します。新しいメッセージにメディア メタデータが含まれている場合は、ファイルをレンダリングまたは開く前に downloadMedia を呼び出します。

downloadMedia は、完全にダウンロードされたバイト数と、必要に応じて表示されるファイル名を返します。DownloadMediaResponse { data: Data, fileName: String? }SDK はダウンロードをキャッシュに保存しません。UI が古いバブルまでスクロール バックしたり、チャットビューに再度入ったりする場合、アプリはデコードされた画像をキャッシュに保存するか、バイトを永続化する必要があります。downloadMedia を再度呼び出すと、別のネットワーク フェッチがトリガーされます。

import Combine

private var cancellables = Set<AnyCancellable>()

CCAI.shared.chatService?.messagesReceived
    .receive(on: DispatchQueue.main)
    .sink { [weak self] messages in
        for message in messages {
            self?.renderIncomingMessage(message)
        }
    }
    .store(in: &cancellables)

func renderIncomingMessage(_ message: ChatMessage) {
    guard let media = message.media else {
        myChatUI.insertTextBubble(text: message.text)
        return
    }

    Task {
        do {
            // `downloadMedia` returns the raw bytes plus an optional filename.
            // First arg is unlabeled.
            let response = try await CCAI.shared.chatService?.downloadMedia(
                media.id,
                mediaType: media.type
            )
            guard let response else { return }

            await MainActor.run {
                switch media.type {
                case .photo:
                    // Decode in-memory - no disk write needed.
                    if let image = UIImage(data: response.data) {
                        myChatUI.insertImageBubble(
                            image: image,
                            fileName: response.fileName
                        )
                    }
                case .video, .audio, .document:
                    // Larger media usually needs an on-disk URL for AVPlayer
                    // or QLPreviewController. Write to the temp directory
                    // yourself and hand the resulting URL to your UI helper.
                    let url = FileManager.default
                        .temporaryDirectory
                        .appendingPathComponent(response.fileName ?? "attachment")
                    try? response.data.write(to: url)
                    myChatUI.insertAttachmentBubble(
                        fileURL: url,
                        mediaType: media.type
                    )
                }
            }
        } catch {
            await MainActor.run {
                myChatUI.insertAttachmentErrorBubble(fileName: message.media?.name)
            }
        }
    }
}

チャット メッセージとメディアのメタデータ型の詳細については、Headless Mobile SDK - iOS API リファレンスをご覧ください。

Deflection(営業時間外と容量超過)

Deflection は、サポートチームが対応できない場合にユーザーをリダイレクトする、コンタクト センターの重要な機能です。通常、これは次の 2 つのシナリオで発生します。

  • 営業時間外: ユーザーが設定された営業時間外にサポートに連絡しようとしています。

  • 容量超過: キューは開いていますが、待ち時間が管理者によって設定された最大しきい値を超えています。

ヘッドレス アーキテクチャでは、SDK はユーザーを自動的にブロックしたり、エラー画面をポップアップしたりしません。代わりに、リダイレクト ステータスと管理者が構成したフォールバック オプションがアプリに渡されます。アプリは、セッションを開始する前にこのステータスを確認する必要があります。

たわみ状態を処理する

SDK が提供するもの: QueueMenu の deflectionFrom: [QueueMenuDeflection]?。他のキューをこのキューに転送する着信転送ルールを一覧表示します。各 QueueMenuDeflection には次の 2 つのフィールドのみが含まれます。

  • deflectionType: DeflectionType? - 転送のカテゴリ(営業時間外、容量超過など)。

  • menuId: Int? - このキューに転送されるソースキューの ID。

QueueMenuDeflection には、表示メッセージや人が読めるラベルは含まれません。ユーザー向けのコピーの場合は、settings 配列を自分でウォークスルーします(または、管理者設定の文字列に戻します)。解決されたソースキューの表示名については、[QueueMenu] の findMenu(byId:) 拡張機能を使用して、すでに取得済みのメニューツリーで検索します。

構築するもの: ユーザーをキューに入れる前にこれらの回避状態を確認するロジックと、適切なメッセージと代替ルーティング ボタンを表示するカスタム UI(全画面アラートやバナーなど)。

実装例

次のコードは、ユーザーがチャットを開始しようとしたときにインターセプトします。QueueMenu で SDK の転送メタデータをチェックし、ルールが有効な場合は、キューの設定から営業時間外のメッセージを解決して転送画面を表示します。

// Helper - pull the first after-hours message text out of the queue's settings
func afterHoursMessageText(for menu: QueueMenu) -> String? {
    return menu.settings?
        .compactMap { $0.afterHours?.message?.text }
        .first
}

// Called when the user taps "Start Chat" in your app
func attemptToStartChat(for menu: QueueMenu) {
    // 1. Check if any deflection rules route into this queue
    if let deflections = menu.deflectionFrom, !deflections.isEmpty {
        let message = afterHoursMessageText(for: menu)
            ?? "Support is currently unavailable."
        showDeflectionScreen(message: message, deflections: deflections)
    } else {
        // No deflection rules apply. Safe to start the chat.
        Task {
            await startChat(for: menu)
        }
    }
}

レンダリングの偏向オプション

転送ルールが有効になっている場合、管理者はユーザーがサポートを受けるための代替手段を設定します。通常は、別のキューを指定する(menuId を使用して解決できます)か、現在のキューの営業時間外のテキストを表示します。

SDK が提供するもの: deflectionFrom の QueueMenuDeflection エントリのリスト。各エントリには deflectionType と menuId が含まれます。

作成するもの: これらのエントリをループ処理し、各 menuId をすでに取得済みのメニューツリーと照合して表示名を取得し、適切なボタンを生成する動的メニュー。

実装例

このコードは、たわみエントリを取得して画面を動的に構築します。[QueueMenu] の SDK 提供の findMenu(byId:) 拡張機能を使用してソースキューの名前を解決し、キュー名が使用できない場合は deflectionType 名にフォールバックします。

func showDeflectionScreen(
    message: String,
    deflections: [QueueMenuDeflection],
    cachedRootMenus: [QueueMenu]
) {
    // 1. Update your UI with the resolved message (or your fallback)
    deflectionTitleLabel.text = message

    // 2. Loop through the incoming deflection rules and generate buttons
    for deflection in deflections {
        let sourceMenu = deflection.menuId.flatMap { cachedRootMenus.findMenu(byId: $0) }
        let label = sourceMenu?.name
            ?? deflection.deflectionType.map { String(describing: $0) }
            ?? "Alternative option"

        let button = createButton(title: label) {
            self.handleDeflectionAction(deflection)
        }
        menuStackView.addArrangedSubview(button)
    }

    // 3. Present the compiled screen to the user
    present(deflectionViewController, animated: true)
}

deflectionFrom は、このメニューにルーティングする転送ルールのリストです。各エントリの menuId は、現在のキューに転送する送信元キューを識別します。これらの表示方法はアプリによって異なります。一部のインテグレーションでは、宛先キューを「代わりにこちらに送信します」と表示しますが、別のインテグレーションでは、ルールが存在するかどうかをゲートとして使用し、「後でやり直してください」という一般的な画面を表示します。