【发布时间】:2021-02-08 05:48:02
【问题描述】:
我想简单地获取计划的本地通知列表并使用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)
【问题讨论】:
-
我试过了,还使用了 group.enter .leave 等,但这些都没有用
标签: ios swiftui unnotificationrequest