---
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


---

# Classe NowChatService : iOS

# Classe NowChatService : iOS {#ariaid-title1}

Rversion finale: Brazil  
Mis à jour 10 sept. 2026  
![](https://www.servicenow.com/docs/portal-asset/ico-clock) 7 minutes de lecture  
La classe NowChatService fournit des options virtuelles et Agent actif de messagerie instantanée.

À l'aide de cette classe, vous pouvez démarrer et arrêter des services de messagerie instantanée, démarrer des sessions de messagerie instantanée, créer une interface utilisateur de messagerie instantanée et vous abonner/vous désabonner des messages non lus.
{#NowChatServiceiOSAPI__entry__2}

| Nom | Description |
|-|-|
| configuration | Paramètres de configuration fournis lors de l'initialisation du service. Type de données : [NowServiceConfiguration](https://servicenow-prod.fluidtopics.net/9cObKA8G_LYnlkCSPBz3eg#NowServiceConfigurationiOSStruct "La structure NowServiceConfiguration définit les informations de configuration d’un service de fonctionnalité.") |
| instanceVersion | Version de l'instance associée ServiceNow , par exemple Vancouver ou Xanadu. Type de données : chaîne |
| networkService (en anglais) | Service réseau associé à ce service de messagerie instantanée. Type de données : NetworkService |
| Type de session | Type de session. Valeurs possibles : * authentifié * invité * Identité empruntée * Inconnu Type de données : SessionType |
[Tableau 1. Propriétés]

## NowChatService : init(configuration : NowServiceConfiguration, délégué : NowChatServiceDelegate ?, coreServiceProvider : NowCoreServiceFournissant ? = néant) {#ariaid-title2}

Initialise une nouvelle instance NowChatService.
{#NChatServ-init_O_S_S__table_jgv_vqp_npb__entry__3}

| Nom | Type | Description |
|-|-|-|
| configuration | [NowServiceConfiguration](https://servicenow-prod.fluidtopics.net/9cObKA8G_LYnlkCSPBz3eg#NowServiceConfigurationiOSStruct "La structure NowServiceConfiguration définit les informations de configuration d’un service de fonctionnalité.") | Informations de configuration nécessaires pour initialiser correctement le service. |
| délégué | NowChatServiceDelegate | Facultatif. Objet délégué de rappel NowChat implémentant le protocole NowChatServiceDelegate. Par défaut : néant |
| coreServiceProvider | NowCoreServiceProviding | Facultatif. Objet implémentant le protocole NowCoreServiceSupplying. Permet d'accéder aux services Now Chat. Par défaut : néant |
[Tableau 2. Paramètres]

{#NChatServ-init_O_S_S__table_jgv_vqp_npb}  
L'exemple de code suivant montre comment appeler cette fonction.

    guard let coreService = NowSDK.core() else {
      // Error with NowServiceError.sdkNotConfigured
      return
    }

    guard 
      let instanceUrl = URL(string: "http://sample.service-now.com"), 
      let serviceConfig = NowSDK.makeServiceConfiguration(for: instanceUrl) else {
        // Could not create service -- 
        // NowServiceError.serviceConfigurationInvalid
        return
      }
        
    let chatService = NowChatService(configuration: serviceConfig, delegate: delegate, coreServiceProvider: coreService)

## NowChatService : makeChatUI(theme : NowChatThemeable, chatConfiguration : NowChatConfiguration ? = nil) -\> Result\<UIViewController, NowChatServiceError\>) {#ariaid-title3}

Crée un `UIViewController` qui héberge l'interface utilisateur de la messagerie instantanée.
Bien que cette fonction crée l'interface utilisateur de la messagerie instantanée, vous devez toujours lancer la session de messagerie instantanée en appelant la fonction [startChat().](https://servicenow-prod.fluidtopics.net/hK8psro0Q9nMQK9_F9GpSA#NChatServ-startChat_O "Démarre une session de messagerie instantanée et exécute un bloc de complétion après le démarrage de la session de messagerie instantanée.") Vous devez passer cet appel lorsque l'interface utilisateur de la messagerie instantanée devient visible. Pour plus d'informations, consultez l'exemple d'application associé et le [Mobile SDK Guide du développeur : iOS](https://servicenow-prod.fluidtopics.net/VI57wrjwMpLiYgKb3ql3Uw "Vous ServiceNow Mobile SDK permet d’exploiter les fonctionnalités et les ressources de la ServiceNow plateforme dans vos applications iOS mobiles autonomes.").
{#NChatServ-makeChatUI_O__table_lkt_lvj_npb__entry__3}

| Nom | Type | Description |
|-|-|-|
| Thème | [Protocole NowChatThemeable : iOS](https://servicenow-prod.fluidtopics.net/5AnB4vXspz05sp2zYKLUew "Le protocole NowChatThemeable fournit des propriétés qui vous permettent de remplacer les couleurs utilisées dans les pages de messagerie instantanée hébergées sur votre ServiceNow instance.") | Informations sur le thème de l'interface utilisateur de messagerie instantanée à créer. |
| messagerie instantanéeConfiguration | [NowChatConfiguration ?](https://servicenow-prod.fluidtopics.net/gGEycCaBYl5vj6u35wgrUQ#NowChatOptionsiOS "Configure les options d’une session de messagerie instantanée.") | Facultatif. Options à appliquer à la session de messagerie instantanée. |
[Tableau 3. Paramètres]

{#NChatServ-makeChatUI_O__table_lkt_lvj_npb} {#NChatServ-makeChatUI_O__table_mkt_lvj_npb__entry__2}

| Type | Description |
|-|-|
| Objet | Réussite : objet UIViewController qui contient les informations de configuration du contrôleur de vue d'interface utilisateur. Échec : objet NowChatServiceError. Erreurs possibles : * chatServiceInvalid * coreServiceInvalid * guestUserNotAllowed * Informations d'identification non valides * noSession * Inconnu * serveur non supporté |
[Tableau 4. Renvoie]

{#NChatServ-makeChatUI_O__table_mkt_lvj_npb}  
L'exemple de code suivant montre comment appeler cette fonction pour créer l'interface utilisateur de la messagerie instantanée.

    func makeChatScreen() -> UIViewController? {
      guard let chatService = chatService else { return nil } 

      let closePrompt = NowChatConfiguration.ClosePrompt(header: "Close Window",
        message: "Are you sure you want to close the chat window?",
        acceptButtonTitle: "Yes",
        declineButtonTitle: "No") 

      let attachmentUploadButton = NowChatConfiguration.AttachmentUploadButton(isVisible: false) // default isVisible = true

      let chatConfiguration = NowChatConfiguration(closePrompt: closePrompt,
        disabledFeatures: [.startNewConversation],
        conversationOptions: [.forceNewConversation, .endConversationOnExit],
        uiConfiguration: NowChatConfiguration.UIConfiguration(closeButton: closeButtonImage(name: "arrow.left"), attachmentUploadButton: attachmentUploadButton))

      let result = chatService.makeChatUI(theme: CarrascoChatTheme(chatColors: ChatColors()), chatConfiguration: chatConfiguration)    

      switch result {
        case .success(let chatViewController):
          return chatViewController
        case .failure(let error):
          debugPrint("Chat screen creation failed with error: \(error)") 
          return nil
      }
    }

## NowChatService : shutdown() {#ariaid-title4}

Arrête le service de messagerie instantanée, y compris toutes les sessions de messagerie instantanée actives.
Après l'appel de cette fonction, le `NowChatService` associé est inactif et ne peut pas être réutilisé. Pour établir une autre session de messagerie instantanée, créez une nouvelle instance `de NowChatService` en appelant la fonction NowChat.makeChatService( ).
{#NChatServ-shutdown__table_zm2_tfk_npb__entry__3}

| Nom | Type | Description |
|-|-|-|
| Aucune |   |   |
[Tableau 5. Paramètres]

{#NChatServ-shutdown__table_zm2_tfk_npb} {#NChatServ-shutdown__table_an2_tfk_npb__entry__2}

| Type | Description |
|-|-|
| Aucune |   |
[Tableau 6. Renvoie]

{#NChatServ-shutdown__table_an2_tfk_npb}  
L'exemple de code suivant montre comment appeler cette fonction.

    private func resetChat() {
      chatService?.shutdown()
      chatService = nil
      initializeChatService()
      viewState = makeViewState()
    }

    func initializeChatService() {
      NowChat.makeChatService(instanceUrl: instanceUrl, delegate: self) { [weak self] result in
        guard let self = self else { return }
                
        switch result {
        case .success(let service):
          self.chatService = service
        case .failure(let error):
          debugPrint("Creating the chat service failed with error: \(error)")
        }
        self.viewState = self.makeViewState()
    }

    func makeViewState() -> ViewState {
      ViewState(chatEnabled: chatService != nil,
        menuItems: menuItems)
    }

## NowChatService : startChat(contextData : \[string : Any\] ? = nil, _ completion : @escaping (Result\<Void, NowChatServiceError\>) -\> Void) {#ariaid-title5}

Démarre une session de messagerie instantanée et exécute un bloc de complétion après le démarrage de la session de messagerie instantanée.
{#NChatServ-startChat_O__table_tk1_bbk_npb__entry__3}

| Nom | Type | Description |
|-|-|-|
| contextData (Données contextuelles) | \[chaîne : n'importe lequel\] ? | Facultatif. Dictionnaire contenant des variables de contexte de messagerie instantanée transmises à la session de messagerie instantanée. Pour plus d'informations sur les variables de contexte de messagerie instantanée, reportez-vous à la section [Live agent chat context variables](https://www.servicenow.com/docs/access?context=live-agent-chat-context-vars&version=brazil&pubname=brazil-conversational-interfaces&ft:locale=en-US). |
| Achèvement | Objet | Bloc d'achèvement à exécuter après le démarrage de la session de messagerie instantanée. |
[Tableau 7. Paramètres]

{#NChatServ-startChat_O__table_tk1_bbk_npb} {#NChatServ-startChat_O__table_uk1_bbk_npb__entry__2}

| Type | Description |
|-|-|
| void ou chaîne | Valeurs renvoyées pour le bloc de complétion : * Réussite : nul * Erreur : NowChatServiceError Erreurs possibles : * chatServiceInvalid * coreServiceInvalid * guestUserNotAllowed * Informations d'identification non valides * noSession * Inconnu * serveur non supporté {#NChatServ-startChat_O__ul_e1n_lpj_k1c} |
[Tableau 8. Renvoie]

{#NChatServ-startChat_O__table_uk1_bbk_npb}  
L'exemple de code suivant montre comment appeler cette fonction sans données de contexte.

    func startChat() {
      guard let chatService = chatService else {
        debugPrint("Chat service is invalid")
        viewState = makeViewState()
        return
      }
      chatService.startChat { [weak self] result in
        if case .failure(let error) = result {
          debugPrint("Chat session initialization failed with error: \(error)")
          self?.resetChat()
        }
      }
    }

    func makeViewState() -> ViewState {
      ViewState(chatEnabled: chatService != nil,
        menuItems: menuItems)
    }

L'exemple de code suivant montre comment appeler cette fonction avec des données de contexte.

    func startChat() {
      guard let chatService = chatService else {
        debugPrint("Chat service is invalid")
        viewState = makeViewState()
        return
      }

      let contextData = ["sys_id": "123456789", "table_name": "wm_task", "active": true] as [String: Any]
      chatService.startChat(contextData: contextData) { [weak self] result in
        if case .failure(let error) = result {
          debugPrint("Chat session initialization failed with error: \(error)")
          self?.resetChat()
        }
      }
    }

    func makeViewState() -> ViewState {
      ViewState(chatEnabled: chatService != nil,
        menuItems: menuItems)
    }

## NowChatService : subscribeToUnreadMessageCount(pollingInterval : TimeInterval, completion : @escaping (Int) -\> Void) {#ariaid-title6}

S'abonne à l'écouteur du nombre de messages non lus.
{#NChatServ-subToUnreadMsgCount_S__table_pv1_3ln_1qb__entry__3}

| Nom | Type | Description |
|-|-|-|
| intervalle d'interrogation | Intervalle de temps | Fréquence à laquelle interroger le service Web pour le nombre de messages de messagerie instantanée non lus. Unité : Secondes |
| Achèvement | @escaping (int) \> nul) | Gestionnaire d'achèvement à appeler pour signaler le nombre de messages de messagerie instantanée non lus. Int: nombre de messages de messagerie instantanée non lus. |
[Tableau 9. Paramètres]

{#NChatServ-subToUnreadMsgCount_S__table_pv1_3ln_1qb} {#NChatServ-subToUnreadMsgCount_S__table_qv1_3ln_1qb__entry__2}

| Type | Description |
|-|-|
| Aucune |   |
[Tableau 10. Renvoie]

{#NChatServ-subToUnreadMsgCount_S__table_qv1_3ln_1qb}  
L'exemple de code suivant montre comment appeler cette fonction.

    ...
    if viewModel.isPolling {
      viewModel.unsubscribeFromUnreadMessageCount()
      viewState.pollingInterval = ""
    } else {
      viewModel.subscribeToUnreadMessageCount(pollingInterval: timeInterval)
    }
    ...

    func subscribeToUnreadMessageCount(pollingInterval: TimeInterval) {
      chatService.subscribeToUnreadMessageCount(pollingInterval: pollingInterval) { [weak self] count in
        self?.unreadMessageCount = count
      }
      isPolling = true
    }

## NowChatService : unsubscribeFromUnreadMessageCount() {#ariaid-title7}

Se désabonne de la réception de l'écouteur du nombre de messages non lus.
{#NChatServ-unsubFromUnreadMsgCount__table_inn_ywn_1qb__entry__3}

| Nom | Type | Description |
|-|-|-|
| Aucune |   |   |
[Tableau 11. Paramètres]

{#NChatServ-unsubFromUnreadMsgCount__table_inn_ywn_1qb} {#NChatServ-unsubFromUnreadMsgCount__table_jnn_ywn_1qb__entry__2}

| Type | Description |
|-|-|
| Aucune |   |
[Tableau 12. Renvoie]

{#NChatServ-unsubFromUnreadMsgCount__table_jnn_ywn_1qb}  
L'exemple de code suivant montre comment appeler cette fonction.

    ...
    if viewModel.isPolling {
      viewModel.unsubscribeFromUnreadMessageCount()
      viewState.pollingInterval = ""
    } else {
      viewModel.subscribeToUnreadMessageCount(pollingInterval: timeInterval)
    }
    ...
    func unsubscribeFromUnreadMessageCount() {
      chatService.unsubscribeFromUnreadMessageCount()
      isPolling = false
      unreadMessageCount = 0
    }

## NowChatService : updateTheme(thème : NowChatThemeable) {#ariaid-title8}

Met à jour le thème de l'interface utilisateur NowChat avec le thème d'interface utilisateur spécifié. Utilisez cette fonction pour mettre à jour le thème de l'interface utilisateur de la messagerie instantanée après qu'il ait été initialement défini à l'aide de la fonction makeChatUI(), par exemple lors du changement du thème de clair à foncé.
{#NChatServ-updateTheme_O__table_r14_1dw_x2c__entry__3}

| Nom | Type | Description |
|-|-|-|
| Thème | [NowChatThemeable](https://servicenow-prod.fluidtopics.net/5AnB4vXspz05sp2zYKLUew "Le protocole NowChatThemeable fournit des propriétés qui vous permettent de remplacer les couleurs utilisées dans les pages de messagerie instantanée hébergées sur votre ServiceNow instance.") | Thème avec lequel mettre à jour l'interface utilisateur de la messagerie instantanée. |
[Tableau 13. Paramètres]

{#NChatServ-updateTheme_O__table_r14_1dw_x2c} {#NChatServ-updateTheme_O__table_s14_1dw_x2c__entry__2}

| Type | Description |
|-|-|
| Aucune |   |
[Tableau 14. Renvoie]

{#NChatServ-updateTheme_O__table_s14_1dw_x2c}  
L'exemple de code suivant montre comment mettre à jour un thème d'interface utilisateur clair vers le thème d'interface utilisateur foncé à l'aide de la fonction updateTheme( ).

    struct LightNowChatColoring: NowChatColoring {
      let nowUIColor: NowUIColoring = LightNowUIColor()
      let brand = UIColor.now_color(withHexString: "#032D42")
      let primary = UIColor.now_color(withHexString: "#00566E")
      let secondary = UIColor.now_color(withHexString: "#002832")
      let destructive = UIColor.now_color(withHexString: "#E52239")
      let textPrimary = UIColor.now_color(withHexString: "#10171A")
      let textSecondary = UIColor.now_color(withHexString: "#232E33")
      let textTertiary = UIColor.now_color(withHexString: "#37444A")
      let textActionable = UIColor.now_color(withHexString: "#ffffff")
      let screenHeaderText = UIColor.now_color(withHexString: "#ffffff")
      let backgroundPrimary = UIColor.now_color(withHexString: "#ffffff")
      let backgroundSecondary = UIColor.now_color(withHexString: "#F5F6F7")
      let backgroundTertiary = UIColor.now_color(withHexString: "#E2E5E7")
      let backgroundPrimaryActionable = UIColor.now_color(withHexString: "#10171A")
      let backgroundSecondaryActionable = UIColor.now_color(withHexString: "#232E33")
      let brandBackground = UIColor.now_color(withHexString: "#BDDEE7")
      let borderTertiary = UIColor.now_color(withHexString: "#d3d6dc")
      let separatorPrimary = UIColor.now_color(withHexString: "#859095")
      let separatorTertiary = UIColor.now_color(withHexString: "#CFD5D7")
      let alertCritical0 = UIColor.now_color(withHexString: "#F9C8CE")
      let alertCritical3 = UIColor.now_color(withHexString: "#E52239")
      let shadow = UIColor.now_color(withHexString: "#10171A")
      let linkPrimary = UIColor.now_color(withHexString: "#1955BE")
      let linkSecondary = UIColor.now_color(withHexString: "#113A82")
      let notification = UIColor.now_color(withHexString: "#E52239")
      let highlightBlue = UIColor.now_color(withHexString: "#C4DBFE")
      let highlightGray = UIColor.now_color(withHexString: "#DCDDDE")
    }

    struct DarkNowChatColoring: NowChatColoring {
      let nowUIColor: NowUIColoring = DarkNowUIColor()
      let brand = UIColor.now_color(withHexString: "#032D42")
      let primary = UIColor.now_color(withHexString: "#6CBBD0")
      let secondary = UIColor.now_color(withHexString: "#99C6D2")
      let destructive = UIColor.now_color(withHexString: "#E46775")
      let textPrimary = UIColor.now_color(withHexString: "#FFFFFF")
      let textSecondary = UIColor.now_color(withHexString: "#E2E5E7")
      let textTertiary = UIColor.now_color(withHexString: "#BCC3C7")
      let textActionable = UIColor.now_color(withHexString: "#050809")
      let backgroundPrimary = UIColor.now_color(withHexString: "#050809")
      let backgroundSecondary = UIColor.now_color(withHexString: "#161F23")
      let backgroundTertiary = UIColor.now_color(withHexString: "#1D272B")
      let backgroundPrimaryActionable = UIColor.now_color(withHexString: "#FFFFFF")
      let backgroundSecondaryActionable = UIColor.now_color(withHexString: "#BCC3C7")
      let brandBackground = UIColor.now_color(withHexString: "#002934")
      let separatorPrimary = UIColor.now_color(withHexString: "#97A2A6")
      let separatorTertiary = UIColor.now_color(withHexString: "#4F5C62")
      let borderTertiary = UIColor.now_color(withHexString: "#454d5b")
      let screenHeaderText = UIColor.now_color(withHexString: "#FFFFFF")
      let alertCritical0 = UIColor.now_color(withHexString: "#7B1D28")
      let alertCritical3 = UIColor.now_color(withHexString: "#E46775")
      let shadow = UIColor.now_color(withHexString: "#10171A")
      let notification = UIColor.now_color(withHexString: "#E46775")
      let linkPrimary = UIColor.now_color(withHexString: "#339EFC")
      let linkSecondary = UIColor.now_color(withHexString: "#70BBFD")
      let highlightBlue = UIColor.now_color(withHexString: "#004652")
      let highlightGray = UIColor.now_color(withHexString: "#363D3D")
    }

    struct LightNowChatTheme: NowChatThemeable {
      let color: NowChatColoring = LightNowChatColoring()
    }

    struct DarkNowChatTheme: NowChatThemeable {
      let color: NowChatColoring = DarkNowChatColoring()
    }

    func chatService(_ chatService: NowChat.NowChatService, systemThemeDidChange traitCollection: UITraitCollection) {
      // The systemThemeDidChange delegate method can be used to call updateTheme() to apply theme changes when the system theme changes.
      debugPrint("System Theme did change")
      chatService.updateTheme(theme: traitCollection.userInterfaceStyle == .dark ? DarkNowChatTheme() : LightNowChatTheme())
    }


