ChatViewModel.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // ChatViewModel.swift
  3. // Chat
  4. //
  5. // Created by Sergey Tarasov on 10.08.2022.
  6. //
  7. import Foundation
  8. import XMPPFramework
  9. import XMPPFrameworkSwift
  10. class ChatViewModelExample {
  11. static let messages: [String] = ["Display a short text message, called an alert, that draws attention to something new in your app.", "Play a notification sound.", "Set a badge number on the app’s icon to let the user know there are new items.", "Provide actions the user can take without opening the app.", "Show a media attachment.", "Be silent, allowing the app to perform a task in the background.", "No", "Group notifications into threads.", "Yes", "Edit or remove delivered notifications.", "Run code to change your notification before displaying it.", "Display a custom, interactive UI for your notification.", "And probably more.", "Yes", "Edit or remove delivered notifications.", "Run code to change your notification before displaying it.", "Display a custom, interactive UI for your notification.", "And probably more."]
  12. }
  13. class ChatViewModel: NSObject, ObservableObject {
  14. let manager: RoomManager
  15. @Published var messageText: String = ""
  16. @Published var messages: [XMPPMessage] = []
  17. init(with jidString: String) {
  18. self.manager = RoomManager(with: jidString)
  19. super.init()
  20. }
  21. func fetchMessages() {
  22. self.manager.fetchMessages()
  23. DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
  24. self?.messages = self?.manager.messages ?? ChatViewModelExample.messages.map { text in
  25. let message = XMPPMessage()
  26. message.addBody(text)
  27. return message
  28. }
  29. }
  30. }
  31. func sendMessage() {
  32. if !self.messageText.isEmpty {
  33. self.manager.room.sendMessage(withBody: self.messageText)
  34. }
  35. }
  36. }
  37. extension ChatViewModel: XMPPRoomDelegate {
  38. func xmppRoom(_ sender: XMPPRoom, didReceive message: XMPPMessage, fromOccupant occupantJID: XMPPJID) {
  39. print(message.debugDescription)
  40. }
  41. }