---
sourceDocument: Referência de API do Brasil
sourceDocumentLink: https://servicenow-prod.fluidtopics.net/r/pt-BR/api-reference

 Release :

    - brazil

ft:locale :

    - pt-BR

ft:publication_title :

    - Referência de API do Brasil

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# Classe do Now ChatService - iOS

# Classe do Now ChatService - iOS {#ariaid-title1}

Versão de lançamento: Brazil  
Atualizado 10 de set. de 2026  
![](https://www.servicenow.com/docs/portal-asset/ico-clock) 7 min. de leitura  
A classe NowChatService fornece Atendente capacidades virtuais e de bate-papo.

Usando esta classe, você pode iniciar e parar serviços de bate-papo, iniciar sessões de bate-papo, criar uma interface de usuário de bate-papo e assinar/cancelar assinatura de mensagens não lidas.
{#NowChatServiceiOSAPI__entry__2}

| Nome | Descrição |
|-|-|
| configuração | Definições de configuração fornecidas quando o serviço foi inicializado. Tipo de dados: [NowServiceConfiguration](https://servicenow-prod.fluidtopics.net/ccI5ZdteLc~VUh2axpIVJA#NowServiceConfigurationiOSStruct "A estrutura do NowServiceConfiguration define informações de configuração para um serviço de recurso.") |
| InstanceVersion | Versão da ServiceNow instância associada, como vancouver ou xanadu. Tipo de dados: Cadeia de caracteres |
| NetworkService | Serviço de rede associado a este serviço de bate-papo. Tipo de dados: NetworkService |
| SessionType | Tipo de sessão. Valores possíveis: * autenticado * convidado * representado * desconhecido Tipo de dados: SessionType |
[Tabela 1. Propriedades]

## NowChatService - init(configuration: NowServiceConfiguration, delegado: NowChatServiceDelegate?, coreServiceProvider: NowCoreServiceProviding? zero) {#ariaid-title2}

Inicializa uma nova instância do NowChatService.
{#NChatServ-init_O_S_S__table_jgv_vqp_npb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| configuração | [NowServiceConfiguration](https://servicenow-prod.fluidtopics.net/ccI5ZdteLc~VUh2axpIVJA#NowServiceConfigurationiOSStruct "A estrutura do NowServiceConfiguration define informações de configuração para um serviço de recurso.") | Informações de configuração necessárias para inicializar corretamente o serviço. |
| delege | ​​​Delegado de serviço do Now Chat | Opcional. Objeto delegado de retorno de chamada do NowChat implementando o protocolo NowChatServiceDelegate. Padrão: Nil |
| CoreServiceProvider | NowCoreServiceProviding | Opcional. Objeto que implementa o protocolo NowCoreServiceProviding. Fornece acesso aos serviços do Now Chat. Padrão: Nil |
[Tabela 2. Parâmetros]

{#NChatServ-init_O_S_S__table_jgv_vqp_npb}  
O exemplo de código a seguir mostra como chamar esta função.

    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? -\> \<UIViewController, NowChatServiceError\>) {#ariaid-title3}

Cria um `UIViewController` que hospeda a interface do usuário do bate-papo.
Embora esta função crie a IU de bate-papo, você ainda deve iniciar a sessão de bate-papo chamando a [](https://servicenow-prod.fluidtopics.net/k0ZJjQfOanf6fNNQoPFfJA#NChatServ-startChat_O "Inicia uma sessão de bate-papo e executa um bloco de conclusão após o início da sessão de bate-papo.") função startChat(). Você deve fazer esta chamada conforme a IU do bate-papo se tornar visível. Para obter mais detalhes, consulte a aplicação de amostra associada e [Mobile SDK Guia do desenvolvedor - iOS](https://servicenow-prod.fluidtopics.net/VnPk153IWOVGw7_5b_JtnQ "O ServiceNow Mobile SDK permite que você aproveite a funcionalidade e os recursos da ServiceNow plataforma em seus aplicativos iOS móveis autônomos.").
{#NChatServ-makeChatUI_O__table_lkt_lvj_npb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| tema | [Protocolo NowChatThemeable - iOS](https://servicenow-prod.fluidtopics.net/6_kEUnt9~gwqy6Whyf4kcA "O protocolo NowChatThemeable fornece propriedades que permitem substituir as cores usadas nas páginas de bate-papo hospedadas em sua ServiceNow instância.") | Informações do tema para a IU do bate-papo criar. |
| Configuração do bate-papo | [NowChatConfiguration?](https://servicenow-prod.fluidtopics.net/8vgSuIpe3arUPtbyy1EPog#NowChatOptionsiOS "Configura opções em uma sessão de bate-papo.") | Opcional. Opções a serem aplicadas à sessão de bate-papo. |
[Tabela 3. Parâmetros]

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

| Tipo | Descrição |
|-|-|
| Object | Objeto UIViewController que contém as informações de configuração do controlador de exibição de IU. Objeto NowChatServiceError. Possíveis erros: * ChatServiceInválido * CoreServiceInválido * GuestUserNotAllowed * Credenciais inválidas * Nenhuma sessão * desconhecido * Servidor incompatível |
[Tabela 4. Retorna]

{#NChatServ-makeChatUI_O__table_mkt_lvj_npb}  
O exemplo de código a seguir mostra como chamar esta função para criar a IU de bate-papo.

    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}

Desliga o serviço de bate-papo, incluindo todas as sessões de bate-papo ativas.
Após chamar esta função, o `Now ChatService associado` está inativo e não pode ser reutilizado. Para estabelecer outra sessão de bate-papo, crie uma nova instância do NowChatService chamando a função NowChat.makeChatService().
{#NChatServ-shutdown__table_zm2_tfk_npb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| Nenhum |   |   |
[Tabela 5. Parâmetros]

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

| Tipo | Descrição |
|-|-|
| Nenhum(a) |   |
[Tabela 6. Retorna]

{#NChatServ-shutdown__table_an2_tfk_npb}  
O exemplo de código a seguir mostra como chamar esta função.

    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: \[Cadeia de caracteres: Qualquer\]? Conclusão: Zero, _ Escapando (\<Void, NowChatServiceError\>) -\> Anular) {#ariaid-title5}

Inicia uma sessão de bate-papo e executa um bloco de conclusão após o início da sessão de bate-papo.
{#NChatServ-startChat_O__table_tk1_bbk_npb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| ContextData | \[Cadeia de caracteres: Qualquer\]? | Opcional. Dicionário que contém variáveis de contexto de bate-papo que são passadas para a sessão de bate-papo. Para obter informações adicionais sobre variáveis de contexto de bate-papo, consulte [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). |
| conclusão | Object | Bloco de conclusão a ser executado após o início da sessão de bate-papo. |
[Tabela 7. Parâmetros]

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

| Tipo | Descrição |
|-|-|
| Cadeia de caracteres ou vazio | Valores de retorno para o bloco de conclusão: * Anulado * NowChatServiceError Possíveis erros: * ChatServiceInválido * CoreServiceInválido * GuestUserNotAllowed * Credenciais inválidas * Nenhuma sessão * desconhecido * Servidor incompatível {#NChatServ-startChat_O__ul_e1n_lpj_k1c} |
[Tabela 8. Retorna]

{#NChatServ-startChat_O__table_uk1_bbk_npb}  
O exemplo de código a seguir mostra como chamar esta função sem dados de contexto.

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

O exemplo de código a seguir mostra como chamar esta função com dados de contexto.

    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: Intervalo de tempo, conclusão: Escape (Int) -\> Vazio) {#ariaid-title6}

Assina o ouvinte de contagem de mensagens não lidas.
{#NChatServ-subToUnreadMsgCount_S__table_pv1_3ln_1qb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| PollingInterval | Intervalo de tempo | A frequência com que o serviço web deve ser pesquisado para a contagem de mensagens de bate-papo não lidas. Unidade: segundos |
| conclusão | (Int) -\> Vazio) | Manipulador de conclusão para chamar para relatar a contagem de mensagens de bate-papo não lidas. IntNúmero de mensagens de bate-papo não lidas. |
[Tabela 9. Parâmetros]

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

| Tipo | Descrição |
|-|-|
| Nenhum(a) |   |
[Tabela 10. Retorna]

{#NChatServ-subToUnreadMsgCount_S__table_qv1_3ln_1qb}  
O exemplo de código a seguir mostra como chamar esta função.

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

O recebimento do ouvinte de contagem de mensagens não lidas é cancelado.
{#NChatServ-unsubFromUnreadMsgCount__table_inn_ywn_1qb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| Nenhum |   |   |
[Tabela 11. Parâmetros]

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

| Tipo | Descrição |
|-|-|
| Nenhum(a) |   |
[Tabela 12. Retorna]

{#NChatServ-unsubFromUnreadMsgCount__table_jnn_ywn_1qb}  
O exemplo de código a seguir mostra como chamar esta função.

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

## NowChatService - updateTheme(tema: NowChatThemeable) {#ariaid-title8}

Atualiza o tema de IU do NowChat com o tema de IU especificado. Use esta função para atualizar o tema de IU de bate-papo depois que ele tiver sido definido inicialmente usando a função makeChatui(), como ao mudar o tema de claro para escuro.
{#NChatServ-updateTheme_O__table_r14_1dw_x2c__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| tema | [NowChatThemeable](https://servicenow-prod.fluidtopics.net/6_kEUnt9~gwqy6Whyf4kcA "O protocolo NowChatThemeable fornece propriedades que permitem substituir as cores usadas nas páginas de bate-papo hospedadas em sua ServiceNow instância.") | Tema para atualizar a IU do bate-papo. |
[Tabela 13. Parâmetros]

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

| Tipo | Descrição |
|-|-|
| Nenhum(a) |   |
[Tabela 14. Retorna]

{#NChatServ-updateTheme_O__table_s14_1dw_x2c}  
O exemplo de código a seguir mostra como atualizar um tema de IU claro para o tema de IU escuro usando a função 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())
    }


