简体   繁体   English

iOS 14 & XCode 12 beta 2 - 从 Firebase 读取数据

[英]iOS 14 & XCode 12 beta 2 - Reading data from Firebase

I'm coding an iOS app with XCode 12 beta 2, and I'm stuck because I need to read some data from Firebase.我正在使用 XCode 12 beta 2 编写 iOS 应用程序,但我被卡住了,因为我需要从 Firebase 读取一些数据。 I took the code by default from Firebase documentation and added some stuff:我默认从 Firebase 文档中获取代码并添加了一些内容:

Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
        
    print("Logged in!")
    
    // Loading Database
    var ref: DatabaseReference!
    ref = Database.database().reference()
        
    let userID = Auth.auth().currentUser?.uid
        
    ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            
        // Get user values
        let value = snapshot.value as? NSDictionary
        let dataFirstname = value?["firstname"] as? String ?? ""
        let dataLastname = value?["lastname"] as? String ?? ""
            
        // Setup labels
        self.namesLabel.text = "\(dataFirstname) \(dataLastname)"
        self.passwordLabel.text = self.password
        self.emailLabel.text = self.email
            
      }) { (error) in
        print(error.localizedDescription)
    }
}

The problem is that "dataFirstname" and "dataLastname" aren't get from the database.问题是“dataFirstname”和“dataLastname”不是从数据库中获取的。 The problem seems to come from the line "let value =....." from what I saw when debugging the code.问题似乎来自我在调试代码时看到的“let value =.....”这一行。 I'm still new at Swift so, any help would be appreciated, Thanks for reading.我还是 Swift 的新手,所以,任何帮助将不胜感激,感谢阅读。 and I hope you'll help me!我希望你能帮助我! -- Max. - 最大限度。

You are getting nil if snapshot.value is not representable as an NSDictionary (which is kind of deprecated in Swift).如果snapshot.value不能表示为 NSDictionary (这在 Swift 中已被弃用),您将得到nil

The quickest way to see the correct type is to log the object: print(snapshot.value)查看正确类型的最快方法是记录 object: print(snapshot.value)

You can also add a breakpoint and inspect the content您还可以添加断点并检查内容

I changed my code but I still need help in a different way Here is what I've done:我更改了我的代码,但我仍然需要以不同的方式获得帮助这是我所做的:

// Loggin-in
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
        
    if error != nil {
            
        // Couldn't log-in
        self.alertUser("Error", error!.localizedDescription)
            
    } else {
            
        print("Logged in!")
        
        // Loading Database
        let userID = Auth.auth().currentUser?.uid
        let db = Firestore.firestore()
        let ref = db.collection("users").document(userID!)

        ref.getDocument { (document, error) in
            if let document = document, document.exists {
                    
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")
                    
                self.FirstName = dataDescription["firstname"]
                self.LastName = dataDescription["lastname"]
                    
                // Setup labels
                self.namesLabel.text = "\(self.FirstName) \(self.LastName)"
                self.passwordLabel.text = self.password
                self.emailLabel.text = self.email
                    
            } else {
                    
                print("Document does not exist")
            }
        }
    }
}

So the problem is that "dataDescription" is a collection with this format: ["lastname": Reikeb, "firstname": Max, "uid": dnefehuzihfz] and I don't know how to take stuff from this collection to put them in separated variables.所以问题是“dataDescription”是一个具有这种格式的集合:[“lastname”:Reikeb,“firstname”:Max,“uid”:dnefehuzihfz] 我不知道如何从这个集合中取出东西来放置它们在分离的变量中。 I already tried with this:我已经尝试过这个:

self.FirstName = dataDescription["firstname"]
self.LastName = dataDescription["lastname"]

but it doesn't work但它不起作用

So I've succeeded to correctly read the data.所以我成功地正确读取了数据。 For those who are interrested in it, here's my final code.对于那些对此感兴趣的人,这是我的最终代码。 Thanks to all the people who helped me!感谢所有帮助过我的人!

// Loggin-in
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
        
    if error != nil {
            
        // Couldn't log-in
        self.alertUser("Error", error!.localizedDescription)
            
    } else {
            
        print("Logged in!")
        
        // Loading Database
        let userID = Auth.auth().currentUser?.uid
        let db = Firestore.firestore()
        let ref = db.collection("users").document(userID!)

        ref.getDocument { (document, error) in
            if let document = document, document.exists {
                    
                var dataDescription = document.data()
                print("Document data: \(dataDescription)")
                    
                // Get values from data
                self.FirstName = dataDescription?.removeValue(forKey: "firstname") as! String
                self.LastName = dataDescription?.removeValue(forKey: "lastname") as! String
                    
                // Setup labels
                self.namesLabel.text = "\(self.FirstName) \(self.LastName)"
                self.passwordLabel.text = self.password
                self.emailLabel.text = self.email
                    
            } else {
                    
                print("Document does not exist")
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM