XMPPController.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // XMPPController.swift
  3. // Chat (iOS)
  4. //
  5. // Created by Sergey Tarasov on 12.10.2022.
  6. //
  7. import XMPPFramework
  8. import XMPPFrameworkSwift
  9. final class XMPPController: NSObject {
  10. static let shared: XMPPController = XMPPController()
  11. let xmppStream: XMPPStream
  12. let xmppReconnect: XMPPReconnect
  13. let xmppRoster: XMPPRoster
  14. let xmppRosterStorage: XMPPRosterMemoryStorage
  15. var xmppAuth: XMPPPlainAuthentication
  16. private override init() {
  17. self.xmppStream = XMPPStream()
  18. self.xmppRosterStorage = XMPPRosterMemoryStorage()
  19. self.xmppRoster = XMPPRoster(rosterStorage: xmppRosterStorage)
  20. self.xmppReconnect = XMPPReconnect()
  21. self.xmppReconnect.activate(xmppStream)
  22. self.xmppRoster.activate(xmppStream)
  23. self.xmppAuth = XMPPPlainAuthentication()
  24. super.init()
  25. self.xmppStream.addDelegate(self, delegateQueue: .main)
  26. self.xmppReconnect.addDelegate(self, delegateQueue: .main)
  27. setupStream()
  28. }
  29. func setupStream() {
  30. self.xmppStream.hostName = "msg.sharix-app.org"
  31. self.xmppStream.hostPort = 5222
  32. self.xmppStream.startTLSPolicy = XMPPStreamStartTLSPolicy.allowed
  33. }
  34. func login(with login: String, and password: String) {
  35. self.xmppStream.myJID = XMPPJID(string: login)
  36. self.xmppAuth = XMPPPlainAuthentication(stream: xmppStream, password: password)
  37. }
  38. func connect() {
  39. if self.xmppStream.isDisconnected {
  40. do {
  41. try xmppStream.connect(withTimeout: XMPPStreamTimeoutNone)
  42. } catch {
  43. }
  44. }
  45. }
  46. }
  47. extension XMPPController: XMPPReconnectDelegate {
  48. func xmppReconnect(_ sender: XMPPReconnect, shouldAttemptAutoReconnect connectionFlags: SCNetworkConnectionFlags) -> Bool {
  49. print("---------- xmppReconnect:shouldAttemptAutoReconnect: ----------")
  50. return true
  51. }
  52. }
  53. extension XMPPController: XMPPStreamDelegate {
  54. func xmppStreamDidConnect(_ sender: XMPPStream) {
  55. do {
  56. try self.xmppStream.authenticate(xmppAuth)
  57. } catch {
  58. }
  59. }
  60. func xmppStreamDidAuthenticate(_ sender: XMPPStream) {
  61. sender.send(XMPPPresence())
  62. print("Stream: Authenticated")
  63. }
  64. }