Classe NowChatService : iOS
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, lancer des sessions de messagerie instantanée, créer une interface utilisateur de messagerie instantanée et vous abonner ou vous désabonner de messages non lus.
| Nom | Description |
|---|---|
| configuration | Paramètres de configuration fournis lors de l’initialisation du service. Type de données : NowServiceConfiguration |
| 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 :
Type de données : SessionType |
NowChatService : init(configuration : NowServiceConfiguration, delegate : NowChatServiceDelegate ?, coreServiceProvider : NowCoreServiceProviding ? = néant)
Initialise une nouvelle instance de NowChatService.
| Nom | Type | Description |
|---|---|---|
| configuration | NowServiceConfiguration | Informations de configuration nécessaires pour initialiser correctement le service. |
| délégué | NowChatServiceDelegate | Facultatif. Objet de délégué de rappel NowChat implémentant le protocole NowChatServiceDelegate. Valeur par défaut : néant |
| coreServiceProvider | NowCoreServiceProviding | Facultatif. Objet implémentant le protocole NowCoreServiceSupplying. Permet d’accéder aux services NowChat. Valeur par défaut : néant |
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>)
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( ). Vous devez passer cet appel lorsque l’interface utilisateur de la messagerie instantanée devient visible. Pour en savoir plus, consultez l’exemple d’application associé et le Mobile SDK Guide du développeur : iOS.
| Nom | Type | Description |
|---|---|---|
| thème | NowChatProtocole à thème : iOS | Informations sur le thème de l’interface utilisateur de messagerie instantanée à créer. |
| chatConfiguration | Configuration de la messagerie instantanée ? | Facultatif. Options à appliquer à la session de messagerie instantanée. |
| 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 :
|
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()
Ferme 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( ).
| Nom | Type | Description |
|---|---|---|
| Aucun |
| Type | Description |
|---|---|
| Aucun |
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, _ complétion : @escaping (Result<Void, NowChatServiceError>) -> Void)
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.
| Nom | Type | Description |
|---|---|---|
| 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. |
| achèvement | Objet | Bloc d’achèvement à exécuter une fois la session de messagerie instantanée démarrée. |
| Type | Description |
|---|---|
| void ou chaîne | Valeurs renvoyées pour le bloc de complétion :
Erreurs possibles :
|
L’exemple de code suivant montre comment appeler cette fonction sans données contextuelles.
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)
S’abonne à l’écouteur du nombre de messages non lus.
| 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) > Vide) | 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. |
| Type | Description |
|---|---|
| Aucun |
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()
Se désabonne de la réception du nombre de messages non lus de l’écouteur.
| Nom | Type | Description |
|---|---|---|
| Aucun |
| Type | Description |
|---|---|
| Aucun |
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(theme : NowChatThemeable)
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 a été initialement défini à l’aide de la fonction makeChatUI(), par exemple lors du changement du thème de clair à foncé.
| Nom | Type | Description |
|---|---|---|
| thème | NowChatThemeable | Thème avec lequel mettre à jour l’interface utilisateur de la messagerie instantanée. |
| Type | Description |
|---|---|
| Aucun |
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())
}