SubscriptionManager.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import Foundation
  2. import FirebaseMessaging
  3. /// Manager to combine persisting a subscription to the data store and subscribing to Firebase.
  4. /// This is to centralize the logic in one place.
  5. struct SubscriptionManager {
  6. private let tag = "Store"
  7. var store: Store
  8. func subscribe(baseUrl: String, topic: String) {
  9. Log.d(tag, "Subscribing to \(topicUrl(baseUrl: baseUrl, topic: topic))")
  10. if baseUrl == Config.appBaseUrl {
  11. Messaging.messaging().subscribe(toTopic: topic)
  12. } else {
  13. Messaging.messaging().subscribe(toTopic: topicHash(baseUrl: baseUrl, topic: topic))
  14. }
  15. let subscription = store.saveSubscription(baseUrl: baseUrl, topic: topic)
  16. poll(subscription)
  17. }
  18. func unsubscribe(_ subscription: Subscription) {
  19. Log.d(tag, "Unsubscribing from \(subscription.urlString())")
  20. DispatchQueue.main.async {
  21. if let baseUrl = subscription.baseUrl, let topic = subscription.topic {
  22. if baseUrl == Config.appBaseUrl {
  23. Messaging.messaging().unsubscribe(fromTopic: topic)
  24. } else {
  25. Messaging.messaging().unsubscribe(fromTopic: topicHash(baseUrl: baseUrl, topic: topic))
  26. }
  27. }
  28. store.delete(subscription: subscription)
  29. }
  30. }
  31. func poll(_ subscription: Subscription) {
  32. poll(subscription) { _ in }
  33. }
  34. func poll(_ subscription: Subscription, completionHandler: @escaping ([Message]) -> Void) {
  35. Log.d(tag, "Polling from \(subscription.urlString())")
  36. ApiService.shared.poll(subscription: subscription) { messages, error in
  37. guard let messages = messages else {
  38. Log.e(tag, "Polling failed", error)
  39. completionHandler([])
  40. return
  41. }
  42. Log.d(tag, "Polling success, \(messages.count) new message(s)", messages)
  43. if !messages.isEmpty {
  44. DispatchQueue.main.sync {
  45. for message in messages {
  46. store.save(notificationFromMessage: message, withSubscription: subscription)
  47. }
  48. }
  49. }
  50. completionHandler(messages)
  51. }
  52. }
  53. }