SubscriptionsListView.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // ContentView.swift
  3. // ntfy-ios
  4. //
  5. // Created by Andrew Cope on 1/15/22.
  6. //
  7. // https://www.hackingwithswift.com/books/ios-swiftui/how-to-combine-core-data-and-swiftui
  8. import SwiftUI
  9. import CoreData
  10. import FirebaseMessaging
  11. struct SubscriptionsList: View {
  12. @Environment(\.managedObjectContext) var context
  13. @FetchRequest(sortDescriptors: [NSSortDescriptor(key: "topic", ascending: true)]) var subscriptions: FetchedResults<Subscription>
  14. var body: some View {
  15. NavigationView {
  16. List {
  17. ForEach(subscriptions) { subscription in
  18. ZStack {
  19. NavigationLink(destination: NotificationListView(subscription: subscription)) {
  20. EmptyView()
  21. }
  22. .opacity(0.0)
  23. .buttonStyle(PlainButtonStyle())
  24. SubscriptionRow(subscription: subscription)
  25. }
  26. .swipeActions(edge: .trailing) {
  27. Button(role: .destructive) {
  28. unsubscribe(subscription)
  29. } label: {
  30. Label("Delete", systemImage: "trash.circle")
  31. }
  32. }
  33. }
  34. }
  35. .listStyle(PlainListStyle())
  36. .navigationTitle("Subscribed topics")
  37. .toolbar {
  38. ToolbarItem(placement: .navigationBarTrailing) {
  39. NavigationLink(
  40. destination: SubscriptionAddView()
  41. ) {
  42. Image(systemName: "plus")
  43. }
  44. }
  45. }
  46. .overlay(Group {
  47. if subscriptions.isEmpty {
  48. Text("No topics")
  49. .font(.headline)
  50. .foregroundColor(.secondary)
  51. }
  52. })
  53. }
  54. .navigationViewStyle(StackNavigationViewStyle())
  55. }
  56. func unsubscribe(_ subscription: Subscription) {
  57. DispatchQueue.main.async {
  58. if let topic = subscription.topic {
  59. Messaging.messaging().unsubscribe(fromTopic: topic)
  60. }
  61. context.delete(subscription)
  62. try? context.save()
  63. }
  64. }
  65. }
  66. /*
  67. struct SubscriptionsList_Previews: PreviewProvider {
  68. static var previews: some View {
  69. SubscriptionsList(
  70. subscriptions: NtfySubscriptionList,
  71. currentView: (.subscriptionList)
  72. )
  73. }
  74. }
  75. */