提问者:小点点

在swift中打印数据库[副本]


我制作了一个应用程序的前端,但现在我必须制作后端,因此打印一个数据库。问题是我出现了一个错误“Failed to get FirebaseApp Instance.请在使用FireStore之前调用FirebaseApp.configure()”:

应用程序代表:

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        FirebaseApp.configure()
        return true
    }
}

数据库:

struct New: Identifiable {
    var id: String = UUID().uuidString
    var news: String
}

class NewsViewModel: ObservableObject {
    @Published var news = [New]()
    
    private var db = Firestore.firestore()
    
    func fetchDate() {
        db.collection("News").addSnapshotListener { (querySnapshot, error) in
            guard let documents = querySnapshot?.documents else {
                print("No documents")
                return
            }
            
            self.news = documents.map { (QueryDocumentSnapshot) -> New in
                let data = QueryDocumentSnapshot.data()
                
                let news = data["News"] as? String ?? "ya r"
                
                return New(news: news)
            }
        }
    }
}

打印数据库:

        NavigationView {
            List(viewModel.news) { news in
                VStack(alignment: .leading) {
                    Text(news.news)
                }
                .navigationTitle("News")
            }
        }
        .onAppear() {
            self.viewModel.fetchDate()
        }

谢谢你的帮助


共1个答案

匿名用户

可以将其添加到WillFinishLaunchingWithOptions中吗

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    FirebaseApp.configure()
    return true
}