Firestore数据库和存储问题 [英] Problem with Firestore database and storage

查看:56
本文介绍了Firestore数据库和存储问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像保存在存储器中,获取该图像的URL,然后在数据库的字段中停止该URL.问题是保存了图像,但没有保存数据库中文档的信息,我尝试延迟存储部分,但没有任何效果.我不确定网址是否是问题所在,似乎图像已经存储,那么重新保存文档就可以了.这是我的功能:任何帮助或指导都将不胜感激(我是编码的新手)

I am trying to save an image in storage, get the URL for that image and then stop the URL in a field in the database. The problem is that the image gets saved, but not the information for the document in the database, I have tried delaying the storage part but nothing works. I am not sure if the url is the issue or not, it seems if the image is already stored, then a re save of the document works. Here is my function: any help or guidance would be appreciated (I am a new to coding)

 @IBAction func submitButtonTapped(_ sender: Any) {
    let db = Firestore.firestore()
    if let userName = Auth.auth().currentUser?.email {
        print(userName)

    func validateFields() -> String? {

                //Check that all fields are filled in
                if mustangNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || blmTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || roundedUpTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || bioTextView.text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""  {
                    return "Please fill in all fields"
                }
            return nil
        }

        let error = validateFields()

        if error != nil {
            // There is something wrong with the fields, show the error message
              let e = error
              print("Error in data, \(String(describing: e))")
              } else {

               //Create cleaned version of the data
               var mustangName = mustangNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
               let blm = blmTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
               let roundedUp = roundedUpTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
               let bio2 = bioTextView.text!.trimmingCharacters(in: .whitespacesAndNewlines)

            let storageRef = Storage.storage().reference().child("Profiles/\(mustangName)")
            if let uploadData = self.profileImageView.image!.pngData() {
            let metaDataForImage = StorageMetadata()
                metaDataForImage.contentType = "image/png"
                storageRef.putData(uploadData, metadata: metaDataForImage, completion: { (metadata, error) in
                        if error != nil {
                        print(error!)
                        return
                        }
                        print(metaDataForImage)
                        } )
                storageRef.downloadURL { (url, error) in
                    guard let downloadURL = url?.absoluteString else {
                           return
                          }
                    if url?.absoluteString != "" {
                        return
                    } else {
                    }
                            print(url!)
                            print("got url")
                    db.collection("Profile").document(mustangName).setData(["mustangName": mustangName,"blm": blm, "roundedUp": roundedUp, "bio2": bio2, "userName": userName, "profileImageURL": url?.absoluteString as Any]) {(error) in
                        if let e = error {
                        print("Error saving user data to firestore, \(e)")
                        } else {
                        print("Successfully saved data for: \(userName)")
                        }
                    }
                    func showError(_ message: String){
                    self.errorLabel.text = message
                    self.errorLabel.alpha = 1
                    }
                }
            }
        }
    }
    //close profile window and go to home screen
       let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController
          self.view.window?.rootViewController = homeViewController
          self.view.window?.makeKeyAndVisible()

}

推荐答案

我强烈建议始终使用代码格式化程序来格式化您的代码,因为这样可以更轻松地发现问题.

I highly recommend always formatting your code with a code formatter, as it makes it much easier to see the problem.

在这种情况下,您需要将获取下载URL的代码移动到Firestore中,并将其写入Firestore中.

In this case, you need to move the code that gets the download URL and writes it to Firestore into the completion handler that runs when the uploading of the file complets:

let storageRef = Storage.storage().reference().child("Profiles/\(mustangName)")
if let uploadData = self.profileImageView.image!.pngData() {
    let metaDataForImage = StorageMetadata()
    metaDataForImage.contentType = "image/png"
    storageRef.putData(uploadData, metadata: metaDataForImage, completion: { (metadata, error) in
        if error != nil {
            print(error!)
            return
        }
        print(metaDataForImage)

        storageRef.downloadURL { (url, error) in
            guard let downloadURL = url?.absoluteString else {
                return
            }
            if url?.absoluteString != "" {
                return
            }
            else {
            }
            print(url!)
            print("got url")
            db.collection("Profile").document(mustangName).setData(["mustangName": mustangName,"blm": blm, "roundedUp": roundedUp, "bio2": bio2, "userName": userName, "profileImageURL": url?.absoluteString as Any]) { (error) in
                if let e = error {
                    print("Error saving user data to firestore, \(e)")
                }
                else {
                    print("Successfully saved data for: \(userName)")
                }
            }
            func showError(_ message: String){
                self.errorLabel.text = message
                self.errorLabel.alpha = 1
            }
        }
    })
}

这篇关于Firestore数据库和存储问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆