【发布时间】:2020-05-20 08:36:45
【问题描述】:
我正在尝试使用 for 循环获取特定的 Firebase 数据,但它给了我这个错误:“'ListenerRegistration' 不能用作符合协议 'View' 的类型,因为 'View' 具有静态要求”。如果调用 ZStack{}.onAppear() 函数,则代码运行。我该如何改变呢?
ForEach(self.allFriends, id: \.id) { friend in
Firestore.firestore().collection(friend.email+"-TodayCal").addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("error fetching: \(error!)")
return
}
let name = documents.map { $0["nameOfFriend"] }
print(name)
self.allFriendsCal.removeAll()
for i in 0..<name.count {
self.allFriendsCal.append(AllFriendsCal(id: UUID(uuidString: documents[i].documentID) ?? UUID(), name: name[i] as? String ?? "Failed to get Name"))
}
}
}
【问题讨论】:
-
ForEach是 SwiftUI 视图的容器。将所有Firestore代码移动到视图模型中。 -
这个
.collection(friend.email+"-TodayCal")可能会出现问题,因为电子邮件可能包含不能用作集合名称的字符。
标签: ios swift xcode firebase swiftui