Classe NowChatService - iOS

  • Versão de lançamento: Zurich
  • Atualizado 31 de jul. de 2025
  • 7 min. de leitura
  • . NowChatService A classe fornece Virtual e. Atendente recursos de bate-papo.

    Usando esta classe, você pode iniciar e interromper 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.

    Tabela 1. Propriedades
    Nome Descrição
    configuração Definições de configuração fornecidas quando o serviço foi inicializado.

    Tipo de dados: NowServiceConfiguration

    InstanceVersion Versão do associado ServiceNow instância, 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
    • guest
    • representado
    • desconhecido

    Tipo de dados: SessionType

    NowChatService - init(configuração: NowServiceConfiguration, delegado: NowChatServiceDelegate?, coreServiceProvider: NowCoreServiceProviding? nulo)

    Inicializa uma nova instância do NowChatService.

    Tabela 2. Parâmetros
    Nome Tipo Descrição
    configuração NowServiceConfiguration Informações de configuração necessárias para inicializar corretamente o serviço.
    delegado ​​​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 NowChat.

    Padrão: Nil

    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(tema: NowChatThemeable, chatConfiguration: NowChatConfiguration? -> <UIViewController, NowChatServiceError>)

    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 StartChat() função. Você deve fazer esta chamada conforme a IU de bate-papo se torna visível. Para obter mais detalhes, consulte a aplicação de amostra associada e Mobile SDK Guia do desenvolvedor - iOS.

    Tabela 3. Parâmetros
    Nome Tipo Descrição
    tema Protocolo NowChatThemeable - iOS Informações do tema para a IU do bate-papo criar.
    ChatConfiguration NowChatConfiguration? Opcional. Opções a serem aplicadas à sessão de bate-papo.
    Tabela 4. Retornos
    Tipo Descrição
    Objeto 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
    • GuestUserNotPermitido
    • Credenciais inválidas
    • Sem Sessão
    • desconhecido
    • Servidor incompatível

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

    Encerra o serviço de bate-papo, incluindo todas as sessões de bate-papo ativas.

    Depois de chamar esta função, o associado NowChatService está inativo e não pode ser reutilizado. Para estabelecer outra sessão de bate-papo, crie uma nova NowChatService chamando NowChat.makeChatService() função.

    Tabela 5. Parâmetros
    Nome Tipo Descrição
    Nenhum
    Tabela 6. Retorna
    Tipo Descrição
    Nenhum(a)

    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: Escape (<Void, NowChatServiceError>) -> Anulado)

    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.

    Tabela 7. Parâmetros
    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.

    conclusão Objeto Bloco de conclusão a ser executado após o início da sessão de bate-papo.
    Tabela 8. Retornos
    Tipo Descrição
    Vazio ou Cadeia de caracteres
    Valores de retorno para o bloco de conclusão:
    • Nulo
    • NowChatServiceError
    Possíveis erros:
    • ChatServiceInválido
    • CoreServiceInválido
    • GuestUserNotPermitido
    • Credenciais inválidas
    • Sem Sessão
    • desconhecido
    • Servidor incompatível

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

    Assina o ouvinte de contagem de mensagens não lidas.

    Tabela 9. Parâmetros
    Nome Tipo Descrição
    PollingInterval Intervalo de tempo Frequência na qual pesquisar o serviço web para a contagem de mensagens de bate-papo não lidas.

    Unidade: segundos

    conclusão (Int) -> Vazamento) Manipulador de conclusão a ser chamado para relatar a contagem de mensagens de bate-papo não lidas.

    IntNúmero de mensagens de bate-papo não lidas.

    Tabela 10. Retornos
    Tipo Descrição
    Nenhum(a)

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

    Cancela a assinatura do recebimento do ouvinte de contagem de mensagens não lidas.

    Tabela 11. Parâmetros
    Nome Tipo Descrição
    Nenhum
    Tabela 12. Retorna
    Tipo Descrição
    Nenhum(a)

    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)

    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 MakeChatui() ao mudar o tema de claro para escuro.

    Tabela 13. Parâmetros
    Nome Tipo Descrição
    tema NowChatThemeable Tema para atualizar a IU do bate-papo.
    Tabela 14. Retornos
    Tipo Descrição
    Nenhum(a)

    O exemplo de código a seguir mostra como atualizar um tema de IU claro para o tema de IU escuro usando UpdateTheme() função.

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