2

我想简单地获取计划的本地通知列表并使用forEach. 我相信它应该像我在下面所做的那样工作,但是数组总是空的,因为它似乎是在 for 循环完成之前使用的。我尝试了getNotifications()使用完成处理程序的函数,也尝试了返回函数,但两种方法仍然无效。我怎样才能等到 for 循环完成来填充我的列表?或者如果有其他方法,请告诉我,谢谢。

var notificationArray = [UNNotificationRequest]()

func getNotifications() {
        
print("getNotifications")
        center.getPendingNotificationRequests(completionHandler: { requests in
            for request in requests {
                print(request.content.title)
                notificationArray.append(request)
            }
        })

}

struct ListView: View {

var body: some View {
    
    NavigationView {
    List {
        ForEach(notificationArray, id: \.content) { notification in

            HStack {
                VStack(alignment: .leading, spacing: 10) {
                    let notif = notification.content
                    Text(notif.title)
                    Text(notif.subtitle)
                    .opacity(0.5)
            }
                    }
        
    }

}
 .onAppear() {
        getNotifications()
    }
}
}

更新:

这是我添加新通知并getNotifications再次调用的方式。我希望列表在创建新数组时动态更新。打印到控制台表明它getNotifications工作正常,并且新数组包含添加的通知。

Section {
                Button(action: {
                    print("Adding Notification: ", title, bodyText, timeIntValue[previewIndex])
                    addNotification(title: title, bodyText: bodyText, timeInt: timeIntValue[previewIndex])
                    showDetail = false
                    self.vm.getNotifications()
                }) {
                    Text("Save Notification")
                }
            }.disabled(title.isEmpty || bodyText.isEmpty)
4

1 回答 1

2

您的全局notificationArray不会被视图观察到。它应该是动态属性......可能的解决方案是将其包装到ObservableObject视图模型中。

这是解决方案的演示:

class ViewModel: ObservableObject {
  @Published var notificationArray = [UNNotificationRequest]()

  func getNotifications() {
        
    print("getNotifications")
        center.getPendingNotificationRequests(completionHandler: { requests in
            var newArray = [UNNotificationRequest]()
            for request in requests {
                print(request.content.title)
                newArray.append(request)
            }
            DispatchQueue.main.async {
              self.notificationArray = newArray
            }
        })
  }
}

struct ListView: View {
  @ObservedObject var vm = ViewModel()
//@StateObject var vm = ViewModel()    // << for SwiftUI 2.0

  var body: some View {
    
    NavigationView {
      List {
        ForEach(vm.notificationArray, id: \.content) { notification in
            HStack {
                VStack(alignment: .leading, spacing: 10) {
                    let notif = notification.content
                    Text(notif.title)
                    Text(notif.subtitle)
                    .opacity(0.5)
                }
            }
      }
   }
   .onAppear() {
        self.vm.getNotifications()
    }
 }
}
于 2020-10-26T04:53:36.887 回答