在Firebase SwiftUI中通过用户名数组过滤查询结果[已关闭]

7bsow1i6  于 2022-11-28  发布在  Swift
关注(0)|答案(1)|浏览(85)

已关闭。此问题需要更多focused。当前不接受答案。
**想要改进此问题吗?**更新问题,使其仅关注editing this post的一个问题。

22小时前关门了。
Improve this question
我有一个从Firestore数据库加载帖子的无限滚动视图。这个提要的目的是像Twitter一样,在那里你可以看到来自被关注用户的帖子列表。
我可以创建一个列表来填充数据库中的所有帖子,但这不是我试图从UI的Angular 来做的。当用户关注一个帐户时,它会将该用户名添加到存储在'followedAccounts'字符串数组中的数组中。
我尝试做的是,当代码执行以获取更多帖子时,它连接到firebase并下载文档(以25个块为单位),这些文档只包含来自'followedAccounts'数组中用户名的帖子
下面是我现在拥有的从Firebase中提取数据的代码。

func loadPosts(amount n: Int) {
    var query: Query
    if documents.count > 0 {
        query = db.collection("posts")
            .order(by: "createdDate", descending: .random())
            .limit(to: n)
            .start(afterDocument: documents.last!)
        print(userFollowedAccounts!.randomElement()!)
    } else {
        query = db.collection("posts")
            .order(by: "createdDate", descending: .random())
             .limit(to: n)
        print(userFollowedAccounts!.randomElement()!)
    }
    query.getDocuments { querySnapshot, error in
        guard let documents = querySnapshot?.documents, error == nil else { return }
        self.documents += documents
    }
}

这是设置要提取的数据量并在视图中显示的视图。

import SwiftUI
import Kingfisher
import LinkPresentation

struct PostView: View {
    @EnvironmentObject var posts: PostsViewModel
    @EnvironmentObject var auth: AuthViewModel
    
    @State private var showNewPost = false
    
    var body: some View {
        ZStack(alignment: .bottomTrailing) {
                VStack {
                    InfiniteScrollView(data: auth.documents, tab: { (post: Post) -> PostTabView in
                        return PostTabView(post: post)
                    }, link: { (post: Post) -> NewPostView in
                        return NewPostView()
                    }, onAppear: {
                        auth.loadPosts(amount: 10)
                    }, onRefresh: {
                        auth.reset()
                        auth.loadPosts(amount: 10)
                    }, onLoadData: { document in
                        auth.loadMorePostsIfNeeded(current: document, amount: 10)
                    })
                }
            
            Button {
                showNewPost.toggle()
            } label: {
                Image(systemName: "pencil")
                    .resizable()
                    .frame(width: 28, height: 28)
                    .padding()
            }
            .background(Color("AppGreen"))
            .foregroundColor(.white)
            .clipShape(Circle())
            .padding()
            .fullScreenCover(isPresented: $showNewPost) {
                NewPostView()
            }
        }
    }
}

下面是无限滚动视图

import SwiftUI
import FirebaseFirestore
import FirebaseFirestoreSwift

struct InfiniteScrollView<Tab: View, Link: View, Data: Codable>: View {
    let data: [DocumentSnapshot]
    let tab: (Data) -> Tab
    let link: (Data) -> Link
    let onAppear: () -> ()
    let onRefresh: () -> ()
    let onLoadData: (DocumentSnapshot) -> ()
    
    init(data: [DocumentSnapshot], tab: @escaping (Data) -> Tab, link: @escaping (Data) -> Link,
         onAppear: @escaping () -> (), onRefresh: @escaping () -> (), onLoadData: @escaping (DocumentSnapshot) -> ()) {
        self.data = data
        self.tab = tab
        self.link = link
        self.onAppear = onAppear
        self.onRefresh = onRefresh
        self.onLoadData = onLoadData
        UITableView.appearance().showsVerticalScrollIndicator = false
    }
    
    var body: some View {
        List {
            ForEach(data, id: \.self) { document in
                let castedDocument = try? document.data(as: Data.self)
                HStack(spacing: 0) {
                    tab(castedDocument!)
                    NavigationLink(destination: link(castedDocument!)) {
                        EmptyView()
                    }
                    .frame(width: 0)
                    .opacity(0)
                    .navigationBarHidden(true) // Removing the banner on the next page (1)
                    .navigationBarTitleDisplayMode(.inline)
                    .navigationBarTitle("")// (2)
                }
                .listRowSeparator(.hidden)
                .listRowBackground(Color.clear)
                .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
                .onAppear {
                    DispatchQueue.main.async {
                        onLoadData(document)
                    }
                }
            }
        }
        .navigationBarHidden(true) // Fixes the refresh (1)
        .navigationBarTitleDisplayMode(.inline)
        .buttonStyle(BorderlessButtonStyle())
        .navigationBarTitle("")// (2)
        .listStyle(.plain)
        .refreshable {
            DispatchQueue.main.async {
                onRefresh()
            }
        }
        .onAppear {
            DispatchQueue.main.async {
                onAppear()
            }
        }
    }
}

我在使用...

.whereField("username", isEqualTo: userFollowedAccounts!.randomElement()!)

这会从数组中生成一个随机索引,并在文档的用户名字段中搜索它。这样做的问题是,它只显示来自该用户的10个帖子。然后显示来自另一个用户的10个帖子。
如果我将限制设置为1,它不会加载更多的文档,并且只显示1个帖子,除非用户手动刷新。
我知道这是一个很大的过程,但我是如此接近得到我想要的,不能越过最后一个障碍。Firebase的文档是有点垃圾在这方面,我正在辩论寻找其他地方为我的帖子饲料。

ccrfmcuu

ccrfmcuu1#

我能够得到它修复感谢一些帮助,从其他网站。所有需要改变的是。whereField需要添加如上所述,你需要创建一个索引的Firebase方面。
代码现在如下所示。

func loadPosts(amount n: Int) {
        var query: Query
        if documents.count > 0 {
            query = db.collection("posts")
                .order(by: "createdTime", descending: true)
                .whereField("userUID", in: User.userFollowedAccounts!)
                .limit(to: n)
                .start(afterDocument: documents.last!)
        } else {
            query = db.collection("posts")
                .order(by: "createdTime", descending: true)
                .whereField("userUID", in: User.userFollowedAccounts!)
                .limit(to: n)
        }
        query.getDocuments { querySnapshot, error in
            guard let documents = querySnapshot?.documents, error == nil else { return }
            self.documents += documents
        }
    }

相关问题