如何在Firebase实时数据库中将一组图像Urls分组在一起? (迅速) [英] How to group an array of Image Urls together in Firebase Realtime Database? (Swift)

查看:85
本文介绍了如何在Firebase实时数据库中将一组图像Urls分组在一起? (迅速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

@IBAction func postFinalButton(_ sender: Any) {
        while index < ImagesOnClick.count {
            ProgressHUD.show()
            ProgressHUD.animationType = .circleRotateChase
            ProgressHUD.colorAnimation = #colorLiteral(red: 0.337254902, green: 0.6156862745, blue: 0.9803921569, alpha: 1)
            ProgressHUD.colorHUD = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        guard let imageSelected = ImagesOnClick[index] else {
            print("Image is nil")
            return
        }
        index += 1
        guard let imageData = imageSelected.jpegData(compressionQuality: 0.4) else {
            print("This is nil")
            return
        }
        let storageRef = Storage.storage().reference(forURL: "gs://loginpage-227bd.appspot.com")
        let storageRefPosts = storageRef.child("posts").child(Auth.auth().currentUser!.uid)
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpg"
        storageRefPosts.putData(imageData, metadata: metadata, completion: {
            (storageMetaData, error) in
            if error != nil {
                
                print("error")
                return
            }
            print("blala")
            storageRefPosts.downloadURL(completion: { (url, error) in
                if let metaImageUrl = url?.absoluteString {
                    print(metaImageUrl)
                    self.sendDataToDatabase(photoUrl: metaImageUrl)
                    //self.performSegue(withIdentifier: "BackToHome", sender: self)
                }
            })
        })
        }
    }
    func sendDataToDatabase(photoUrl: String) {
        let ref = Database.database().reference()
        let postsRefrence = ref.child("posts")
        let newPostId = postsRefrence.childByAutoId().key
        let newPostsRefrence = postsRefrence.child(newPostId!)
        newPostsRefrence.setValue(["photoUrl": photoUrl], withCompletionBlock: {
            (error, ref) in
            if error != nil {
                ProgressHUD.showError(error?.localizedDescription)
                return
            }
            ProgressHUD.showSucceed()
        })
    }

我的模型如下:

如果查看数据库,您将在单独的ID中看到4张不同的图像。问题是我同时上传了所有这些图像。我正在尝试创建一个应用,您可以在其中发布图像,然后查看它们。但是,如果我将多个图像上传在一起,它们将存储为完全独立的图像。我想要的是,如果用户上传他们存储在一起的图像数组,那么我可以将它们作为一个帖子检索出来。我的问题是我该怎么做?

If you look at the database you will see 4 different images each one in a separate Id. The problem is I uploaded these images all at the same time. I am trying to create an app where you can post images and then view them. However if I upload multiple images together they get stored as completely separate images. What I want is if the user uploads an array of images they get stored together so I can retrieve them as one post. My question is how would I do that?

编辑

我将代码更改为:

@IBAction func postFinalButton(_ sender: Any) {
        let ref = Database.database().reference()
        let postsReference = ref.child("posts")
        let newImagesRef = postsReference.childByAutoId()
        while index < ImagesOnClick.count {
            ProgressHUD.show()
            ProgressHUD.animationType = .circleRotateChase
            ProgressHUD.colorAnimation = #colorLiteral(red: 0.337254902, green: 0.6156862745, blue: 0.9803921569, alpha: 1)
            ProgressHUD.colorHUD = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        guard let imageSelected = ImagesOnClick[index] else {
            print("Image is nil")
            return
        }
        index += 1
        guard let imageData = imageSelected.jpegData(compressionQuality: 0.4) else {
            print("This is nil")
            return
        }
        let storageRef = Storage.storage().reference(forURL: "gs://loginpage-227bd.appspot.com")
        let storageRefPosts = storageRef.child("posts").child(Auth.auth().currentUser!.uid)
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpg"
        storageRefPosts.putData(imageData, metadata: metadata, completion: {
            (storageMetaData, error) in
            if error != nil {
                
                print("error")
                return
            }
            print("blala")
            storageRefPosts.downloadURL(completion: { (url, error) in
                if let metaImageUrl = url?.absoluteString {
                    print(metaImageUrl)
                    self.sendDataToDatabase(photoUrl: metaImageUrl, ref: postsReference, index: self.index)
                    //self.performSegue(withIdentifier: "BackToHome", sender: self)
                }
            })
        })
        }
    }
    func sendDataToDatabase(photoUrl: String, ref: DatabaseReference, index: Int) {
        let name = "photoUrl"+String(index)
        ref.setValue([name: photoUrl], withCompletionBlock: {
            (error, ref) in
            if error != nil {
                ProgressHUD.showError(error?.localizedDescription)
                return
            }
            ProgressHUD.showSucceed()
        })
    }

但是现在当我只按下发布按钮时最后选择的图片网址将被保存,而不是将每个帖子存储在新的ID下,而是将其存储在posts子项下。这是它的外观图像:

But now when I press the post button only the last selected image url is saved, and instead of each post being stored under a new id they are stored under the posts child. Here is an image of what it looks like:

推荐答案

每次调用 childByAutoId()都会生成一个新的唯一在数据库中的位置。因为您现在为每个图像调用 childByAutoId(),所以每个图像都以其自己的自动ID存储。

Every time you call childByAutoId() it generates a new unique location in the database. Since you now call childByAutoId() for every image, each image gets stored under its own auto ID.

诀窍是仅为所有图像调用一次 childByAutoId()。但这意味着您需要为每个图像使用另一个唯一的属性名称,因为它们不能全部称为 photoUrl (键在其父节点中必须是唯一的)

The trick is to only call childByAutoId() once for all images. But that means you'll need to use another unique property name for each image, as they can't all be called photoUrl (keys have to be unique in their parent node).

一种方法是:


  1. 调用 childByAutoId() postFinalButton 方法中一次,然后将生成的密钥传递到 sendDataToDatabase

  2. 使用每个文件的索引作为文件名的一部分,方法是将该值也传递到 sendDataToDatabase

  1. Call childByAutoId() once in the postFinalButton method, and pass the resulting key into sendDataToDatabase.
  2. Use the index of each file as part of its filename, by also passing that value into sendDataToDatabase.

postFinalButton 中是这样的:

let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newImagesRef = postsRefrence.childByAutoId()

...

storageRefPosts.putData(imageData, metadata: metadata, completion: {
    (storageMetaData, error) in
    if error != nil {            
        print("error")
        return
    }
    storageRefPosts.downloadURL(completion: { (url, error) in
        if let metaImageUrl = url?.absoluteString {
            self.sendDataToDatabase(photoUrl: metaImageUrl, newImagesRef, index)
        }
    })
})

然后:

func sendDataToDatabase(photoUrl: String, ref: DatabaseReference, index: int) {
    let name = "photoUrl"+String(index)
    ref.setValue([name: photoUrl], withCompletionBlock: {
        (error, ref) in
        if error != nil {
            ProgressHUD.showError(error?.localizedDescription)
            return
        }
        ProgressHUD.showSucceed()
    })
}

这篇关于如何在Firebase实时数据库中将一组图像Urls分组在一起? (迅速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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