如何解决如何在SwiftUI中接收NotificationCenter发布
我看过十几本有关如何使用合并并接收Notification
完成的任务的教程。似乎它们都显示线性代码-发布者和接收者都在同一位置,一行一行。
发布通知与以下代码一样简单:
// background download task complete - notify the appropriate views
DispatchQueue.main.async {
NotificationCenter.default.post(name: .dataDownloadComplete,object: self,userInfo: self.dataCounts)
}
extension Notification.Name {
static let dataDownloadComplete = Notification.Name("dataDownloadComplete")
}
SwiftUI具有onReceive()
修饰符,但我找不到将以上内容与发布的通知的“监听器”相关的任何方法。
View
如何收到此Notification
解决方法
仅供参考,经过几天的阅读并整理了令人困惑的“合并”教程,我发现了这两种接收通知的方法。为方便起见,它们包含在同一视图中。 (一些无关的细节已被省略。)
在我的情况下,提取(在后台线程上执行)是将多个实体的信息批量加载到Core Data中。提取完成后,视图尚未更新。
// in the background fetch download class
...
var dataCounts: [DataSources.Source : Int] = [:]
...
// as each source of data has been imported
self.dataCounts[source] = numberArray.count
...
// in a view
import Combine
struct FilteredPurchasesView: View {
private var downloadCompletePublisher: AnyPublisher<Notification,Never> {
NotificationCenter.default
.publisher(for: .dataDownloadComplete)
.eraseToAnyPublisher()
}
private var publisher = NotificationCenter.default
.publisher(for: .dataDownloadComplete)
.map { notification in
return notification.userInfo as! [DataSources.Source : Int]
}
.receive(on: RunLoop.main)
var body: some View {
List {
ForEach(numbers.indices,id: \.self) { i in
NavigationLink(destination: NumberDetailView(number: numbers[i])) {
NumberRowView(number: numbers[i])
}
.id(i)
}
}
.add(SearchBar(searchText: $numberState.searchText))
.onReceive(downloadCompletePublisher) { notification in
print("dataDownload complete (FilteredPurchasesView 1)")
if let info = notification.userInfo as? [DataSources.Source:Int],let purchaseCount = info[DataSources.Source.purchased] {
if purchaseCount > 0 {
// now the view can be updated/redrawn
} else {
print("purchase update count = 0")
}
}
}
.onReceive(publisher) { notification in
print("dataDownload complete (FilteredPurchasesView 2)")
}
}
}
关于此的一些注释:
- 在前几次尝试中,FilteredPurchasesView尚未初始化。这意味着没有订阅者可以收听发布的通知。
- 两个Publisher变量都可用。在撰写本文时,我无法解释它们为什么或如何工作。
- 两个
onReceive()
修饰符均包含通知。
欢迎评论,想法和反馈。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。