我想简单地获取计划的本地通知列表,并使用forEach填充SwiftUI列表。我相信它应该像我下面所做的那样工作,但是数组总是空的,因为它似乎是在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)发布于 2020-10-26 12:53:37
视图不会观察到您的全局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()
}
}
}https://stackoverflow.com/questions/64529191
复制相似问题