---
sourceDocument: Référence API Brésil
sourceDocumentLink: https://servicenow-prod.fluidtopics.net/r/fr-FR/api-reference

 Release :

    - brazil

ft:locale :

    - fr-FR

ft:publication_title :

    - Référence API Brésil

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# Intégrer un agent vocal IA avec NowVoice

# Intégrer un agent vocal IA avec NowVoice {#ariaid-title1}

Rversion finale: Brazil  
Mis à jour 10 sept. 2026  
![](https://www.servicenow.com/docs/portal-asset/ico-clock) 5 minutes de lecture  
Utilisez le module NowVoice pour intégrer une session d'agent vocal IA en temps réel dans votre iOS application.

## Fonctionnalités de NowVoice

NowVoice fournit à votre application une interface utilisateur d'agent vocal complète et prête à être présentée. Lorsqu'un utilisateur démarre une session d'agent vocal, le SDK :

* S'authentifie auprès de votre ServiceNow instance à l'aide du jeton fourni par votre application.
* Ouvre une connexion WebSocket au point de terminaison d'agent vocal configuré.
* Affiche une vue SwiftUI native en plein écran avec des commandes de microphone et une transcription en direct.
* Fournit des messages de transcription en temps réel et des changements d'état de sourdine à votre application via des rappels.
* Affiche un écran de résumé de la transcription post-appel facultatif à la fin de la session.

## Thématisation {#mobsdk-ios-nowvoice__section_qsn_p12_zjc}

NowVoice s'intègre au système de thématisation NowUI. Passez n'importe quel type conforme à [`NowVoiceThemeable`](https://servicenow-prod.fluidtopics.net/0azi8x6OVh8JohmNDAUvXA "Définit les couleurs à appliquer aux éléments d’interface utilisateur NowVoice.") pour appliquer des couleurs personnalisées. [`NowVoiceDefaultTheme`](https://servicenow-prod.fluidtopics.net/Xsz0quABl9SEFFuJUlgfHA#NVoiceDefThemeiOSStruct "Implémentation par défaut de NowVoiceThemeable.") est fourni par défaut.

## Intégration de NowChat {#mobsdk-ios-nowvoice__section_rsn_p12_zjc}

Si votre application utilise NowChat, vous pouvez activer NowVoice dans l'interface de messagerie instantanée. Définissez [`les propriétés NowChatConfiguration`](https://servicenow-prod.fluidtopics.net/gGEycCaBYl5vj6u35wgrUQ#NowChatOptionsiOS "Configure les options d’une session de messagerie instantanée.") pour configurer les fonctions vocales dans l'interface utilisateur Now Chat et ajouter un bouton vocal. Appuyez dessus pour lancer l'interface utilisateur de l'agent vocal en tant que superposition plein écran dans le flux de messagerie instantanée.

## Mobile SDK Paramètres de l'instance {#mobsdk-ios-nowvoice__section_ys3_4k2_zjc}

Le module NowVoice lit les clés suivantes à partir de la réponse des paramètres de votre ServiceNow instance Mobile SDK .

    {
      "sdk": {
        "voice": {
          "enabled": true,
          "configurations": [
            {
              "voiceServiceId": "String",
              "voiceWebhookURL": "String",
              "mobileChannelType": "String",
              "mobileChannelId": "String"
            }
          ]
        }
      }
    }

## Configurer NowVoice {#ariaid-title2}

Configurez NowVoice pour ajouter un agent vocal en temps réel à votre iOS application.

### Avant de commencer

Rôle requis : admin

* Mobile SDK La version 2.22.0 ou ultérieure doit être ajoutée à votre projet Xcode via le gestionnaire de packages SWIFT.
* Les services d'agent vocal doivent être activés sur votre ServiceNow instance. Confirmez que `sdk.voice.enabled` est `vrai` dans les Mobile SDK paramètres.

### Procédure

1. Ajoutez une description de l'utilisation du microphone.  
   Ajoutez la clé `NSMicrophoneUsageDescription` à l'info.plist de votre application :  

       <key>NSMicrophoneUsageDescription</key>
       <string>This app uses your microphone to communicate with the ServiceNow voice agent.</string>

   Remarque :  
   Omettre cette touche peut entraîner iOS le blocage de l'application au début de la session vocale.
2. Configurez NowSDK.  
   Si vous ne l'avez pas déjà fait, configurez NowSDK une fois au lancement de l'application. NowVoice nécessite que NowSDK soit configuré avant toute opération vocale.
   1. Appelez [`NowSDK.configure(with :).`](https://servicenow-prod.fluidtopics.net/z78aHVLAACbqCz23Rh7h1g#NSDK-configure_O "Configure NowSDK pour utilisation. Vous devez appeler cette fonction avant d’appeler l’un des services d’entités dans .Mobile SDK")  

          import NowSDK

          try NowSDK.configure(with: NowSDKConfiguration(
              authorizationProvider: self,
              permissionDelegate: self,
              logLevel: .error
          ))

   2. Implémenter `NowSDKAuthorizationFournir` pour fournir des jetons OAuth pour votre instance.  

          func requestAuthorization(for instanceUrl: URL, completion: @escaping ([AuthorizationToken]?) -> Void) {
              // Retrieve and return your OAuth tokens here.
              completion(yourTokens)
          }

   3. Implémentez `DevicePermissionDelegate` pour autoriser l'accès au microphone.  

          func canRequestPermission(_ permission: DevicePermission) -> Bool {
              return true
          }

3. Créez un NowVoiceService.  
   Importez NowVoice et appelez [`makeVoiceService(instanceUrl :)`](https://servicenow-prod.fluidtopics.net/gCOQu_dqUck6Gi5RttHpVw#NVoice-makeVoiceService_S "Crée une instance de NowVoiceService pour l’instance spécifiée ServiceNow .") avec l'URL de votre ServiceNow instance. Il s'agit d'une fonction asynchrone ; à partir d'un contexte asynchrone ou d'une tâche.  

       import NowVoice

       let instanceUrl = URL(string: "https://your-instance.service-now.com")!

       do {
           let voiceService = try await NowVoice.makeVoiceService(instanceUrl: instanceUrl)
       } catch {
           // Handle NowServiceError
           print("Failed to create voice service: \(error)")
       }

4. Sélectionnez un point de terminaison de fonctions vocales.  
   Utilisez [`NowVoiceService.configurations`](https://servicenow-prod.fluidtopics.net/kfFHin7buE1rtJ7Zq765pw#NowVoiceServiceiOSAPI "La classe NowVoiceService gère les sessions de l’agent vocal pour une seule ServiceNow instance.") pour récupérer les points de terminaison vocaux disponibles. Dans la plupart des applications, il existe un seul point de terminaison.  

       guard let endpoint = voiceService.configurations.first else {
           // No voice endpoints configured on this instance.
           return
       }

5. Lancez l'interface utilisateur vocale.  
   Appelez [`startVoice(endpoint :uiConfiguration :callbacks :theme :)`](https://servicenow-prod.fluidtopics.net/kfFHin7buE1rtJ7Zq765pw#NVoiceServ-startVoice_O_O_O_O "Crée un UIViewController contenant l’interface utilisateur de l’agent vocal, prêt à être présenté dans un modal.") pour obtenir un `UIViewController` avec l'interface utilisateur de l'agent vocal. Présentez-le en plein écran.  

       let vc = try await voiceService.startVoice(
           endpoint: endpoint,
           uiConfiguration: NowVoiceUIConfiguration(
               hidesPostCallTranscript: false,
               shouldBlockTranscriptSharing: false
           ),
           callbacks: NowVoiceCallbacks(
               onMuteStateChanged: { isMuted in
                   // Update your UI to reflect the current mute state.
                   print("Microphone muted: \(isMuted)")
               },
               onMessageReceived: { message in
                   // Receive real-time transcript messages during the session.
                   print("[\(message.role)]: \(message.content)")
               },
               onCallEnded: { conversationId, error, endedFromCallKitUI in
                   // Called when the voice session ends.
                   if let error {
                       print("Session ended with error: \(error)")
                   } else {
                       print("Session complete. Conversation ID: \(conversationId ?? "unknown")")
                   }
               },
               onCallMinimized: {
                   // Called when the voice UI is minimized.
                   print("Voice chat is minimized")
               }
           ),
           theme: NowVoiceDefaultTheme()
       )

       vc.modalPresentationStyle = .fullScreen
       present(vc, animated: true)

   Remarque :  
   `startVoice()` extrait automatiquement un jeton d'accès OAuth avant de lancer l'interface utilisateur vocale.
6. **Facultatif :** Appliquez un thème personnalisé.  
   Pour faire correspondre l'interface utilisateur vocale à l'identité visuelle de votre application, créez un type conforme à [`NowVoiceThemeable`](https://servicenow-prod.fluidtopics.net/0azi8x6OVh8JohmNDAUvXA "Définit les couleurs à appliquer aux éléments d’interface utilisateur NowVoice.") et transmettez-le à [`startVoice(endpoint :uiConfiguration :callbacks :theme :)`](https://servicenow-prod.fluidtopics.net/kfFHin7buE1rtJ7Zq765pw#NVoiceServ-startVoice_O_O_O_O "Crée un UIViewController contenant l’interface utilisateur de l’agent vocal, prêt à être présenté dans un modal.") ou [`updateTheme(theme :).`](https://servicenow-prod.fluidtopics.net/kfFHin7buE1rtJ7Zq765pw#NVoiceServ-updateTheme_O "Met à jour le thème visuel de l’interface utilisateur vocale actuellement active.")  

       struct MyVoiceTheme: NowVoiceThemeable {
           var color: NowUIColoring = MyAppColors()
       }

       // Apply at voice session launch
       let vc = try await voiceService.startVoice(endpoint: endpoint, theme: MyVoiceTheme())

       // Or update while a voice session is active
       voiceService.updateTheme(theme: MyVoiceTheme())

7. **Facultatif :** Intégrez la voix dans NowChat.  
   Si votre application utilise déjà NowChat, vous pouvez activer NowVoice dans l'interface de messagerie instantanée. Transmettez la configuration vocale directement à [`NowChatConfiguration`](https://servicenow-prod.fluidtopics.net/gGEycCaBYl5vj6u35wgrUQ#NowChatOptionsiOS "Configure les options d’une session de messagerie instantanée."). Un bouton vocal apparaît automatiquement dans l'interface utilisateur de la messagerie instantanée lorsqu'un point de terminaison vocal valide est fourni.  
   Remarque :  
   Lorsque vous utilisez NowChat avec la fonction vocale, n'appelez pas [`startVoice(endpoint :uiConfiguration :callbacks :theme :)`](https://servicenow-prod.fluidtopics.net/kfFHin7buE1rtJ7Zq765pw#NVoiceServ-startVoice_O_O_O_O "Crée un UIViewController contenant l’interface utilisateur de l’agent vocal, prêt à être présenté dans un modal.") pour lancer l'interface utilisateur vocale. NowChat gère le cycle de vie des sessions vocales en interne.  

       import NowChat
       import NowVoice

       // voiceConfiguration is optional --- omit it to have the SDK use instance settings automatically
       let chatConfig = NowChatConfiguration(
           closePrompt: NowChatConfiguration.ClosePrompt(
               header: "Leave chat?",
               message: "Your conversation will end.",
               acceptButtonTitle: "Leave",
               declineButtonTitle: "Stay"
           ),
           disabledFeatures: [],
           conversationOptions: [.forceNewConversation],
           uiConfiguration: NowChatConfiguration.UIConfiguration(
               closeButton: .text("Close"),
               attachmentUploadButton: .init(isVisible: true),
               hideBranding: false
           ),
           voiceConfiguration: voiceService.configurations.first, // optional endpoint override
           voiceUIConfiguration: NowVoiceUIConfiguration(
               hidesPostCallTranscript: false,
               shouldBlockTranscriptSharing: false
           ),
           voiceCallbacks: NowVoiceCallbacks(
               onMuteStateChanged: { isMuted in
                   print("Muted: \(isMuted)")
               },
               onMessageReceived: { message in
                   print("Transcript: \(message)")
               },
               onCallEnded: { conversationId, error, endedFromCallKitUI in
                   // Called when the embedded voice session ends
               },
               onCallMinimized: {
                   // Called when the voice UI is minimized.
                   print("Voice chat is minimized")
               }
           )
       )

       let chatVC = try await chatService.startChat(configuration: chatConfig)
       present(chatVC, animated: true)

### Résultats

L'interface utilisateur de l'agent vocal est présentée en plein écran. L'utilisateur peut démarrer une session vocale en temps réel avec des mises à jour de transcription et d'état de sourdine fournies à votre application via les rappels configurés.

### Exemple complet

    import NowSDK
    import NowVoice

    // --- App launch ---
    try NowSDK.configure(with: NowSDKConfiguration(
        authorizationProvider: self,
        permissionDelegate: self
    ))

    // --- When the user taps "Start Voice" ---
    func startVoiceSession() async {
        let instanceUrl = URL(string: "https://your-instance.service-now.com")!

        do {
            let voiceService = try await NowVoice.makeVoiceService(instanceUrl: instanceUrl)

            guard let endpoint = voiceService.configurations.first else { return }

            let vc = try await voiceService.startVoice(
                endpoint: endpoint,
                callbacks: NowVoiceCallbacks(
                    onMuteStateChanged: { [weak self] isMuted in
                        self?.updateMuteIndicator(isMuted: isMuted)
                    },
                    onMessageReceived: { [weak self] message in
                        self?.appendTranscript(message)
                    },
                    onCallEnded: { [weak self] _, error, endedFromCallKitUI in
                        self?.dismiss(animated: true)
                    },
                    onCallMinimized: {
                        // Called when the voice UI is minimized.
                        print("Voice chat is minimized")
                    }
                )
            )
            vc.modalPresentationStyle = .fullScreen
            present(vc, animated: true)

        } catch let error as NowServiceError {
            handleServiceError(error)
        }
    }


