我有一个使用 firebase 的 swiftui 应用程序。我想在向用户发布帖子时按城市进行过滤。为此,我将城市参数添加到 firebase 集合中。然后我想使用 whereField 向用户显示,但由于某种原因什么也没有发生。这是我的代码:
struct ReusablePostViewContentView: View {
var cities = ["Москва", "Волгоград", "Пермь"]
@State private var selectedCity: String = "Москва"
@Binding var posts: [Post]
@State private var isFetching: Bool = true
@State private var paginationDoc: QueryDocumentSnapshot?
var body: some View {
Picker("Выберите город", selection: $selectedCity) {
ForEach(cities, id: \.self) {
Text($0)
}
}
ScrollView(.vertical, showsIndicators: false) {
LazyVStack {
if isFetching {
ProgressView()
.padding(.top, 30)
} else {
if posts.isEmpty {
Text("Записи отсутствуют")
.font(.caption)
.foregroundColor(.gray)
.padding(.top, 30)
} else {
Posts()
}
}
}
.padding(15)
}
.refreshable {
isFetching = true
posts = []
paginationDoc = nil
await fetchPosts()
}
.task {
guard posts.isEmpty else {return}
await fetchPosts()
}
}
}
func Posts() -> some View {
ForEach (posts) { post in
PostCardViewContentViewFish(post: post) { updatedPost in
if let index = posts.firstIndex(where: { post in
post.id == updatedPost.id
}) {
posts[index].likedIDs = updatedPost.likedIDs
posts[index].dislikedIDs = updatedPost.dislikedIDs
}
} onDelete: {
withAnimation(.easeInOut(duration: 0.25)) {
posts.removeAll {post.id == $0.id}
}
}
.onAppear {
if post.id == posts.last?.id && paginationDoc != nil {
Task {await fetchPosts()}
}
}
Divider()
.padding(.horizontal, -15)
}
}
func fetchPosts() async {
do {
var query: Query!
if let paginationDoc {
query = Firestore.firestore().collection("Posts")
.whereField("yourCity", isEqualTo: selectedCity)
.order(by: "upPostPlusDayValueCount", descending: true)
.start(afterDocument: paginationDoc)
.limit(to: 5)
} else {
query = Firestore.firestore().collection("Posts")
.whereField("yourCity", isEqualTo: selectedCity)
.order(by: "upPostPlusDayValueCount", descending: true)
.limit(to: 5)
}
let docs = try await query.getDocuments()
let fetchedPosts = docs.documents.compactMap { doc -> Post? in
try? doc.data(as: Post.self)
}
await MainActor.run(body: {
posts.append(contentsOf: fetchedPosts)
paginationDoc = docs.documents.last
isFetching = false
})
} catch {
print(error.localizedDescription)
}
}
}