TopicView.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import SwiftUI
  15. import FirebaseMessaging
  16. struct TopicView: View {
  17. @State private var topic: String = ""
  18. @State private var result: String = ""
  19. var body: some View {
  20. VStack {
  21. List {
  22. Text("Topic")
  23. .font(.title).bold()
  24. .foregroundColor(.blue)
  25. TextField("Enter your topic", text: $topic)
  26. .textFieldStyle(RoundedBorderTextFieldStyle())
  27. Text("\(result)")
  28. .lineLimit(10)
  29. .multilineTextAlignment(.leading)
  30. }
  31. Button(action: subscribe) {
  32. HStack {
  33. Image(systemName: "t.bubble.fill").font(.body)
  34. Text("Subscribe")
  35. .fontWeight(.semibold)
  36. }
  37. }
  38. Button(action: unsubscribe) {
  39. HStack {
  40. Image(systemName: "bin.xmark.fill").font(.body)
  41. Text("Unsubscribe")
  42. .fontWeight(.semibold)
  43. }
  44. }
  45. Button(action: clear) {
  46. HStack {
  47. Image(systemName: "clear").font(.body)
  48. Text("Clear ")
  49. .fontWeight(.semibold)
  50. }
  51. }
  52. }
  53. .buttonStyle(IdentityButtonStyle())
  54. }
  55. func subscribe() {
  56. Messaging.messaging().subscribe(toTopic: topic) { error in
  57. if let error = error as NSError? {
  58. self.result = "Failed subscription: \(error)"
  59. return
  60. }
  61. self.result = "Successfully subscribe \(self.topic)."
  62. }
  63. }
  64. func unsubscribe() {
  65. Messaging.messaging().unsubscribe(fromTopic: topic) { error in
  66. if let error = error as NSError? {
  67. self.result = "Failed unsubscription: \(error)"
  68. return
  69. }
  70. self.result = "Successfully unsubscribe \(self.topic)"
  71. }
  72. }
  73. func clear() {
  74. result = ""
  75. }
  76. }
  77. struct TopicView_Previews: PreviewProvider {
  78. static var previews: some View {
  79. Group {
  80. TopicView()
  81. }
  82. }
  83. }