将图像url数组附加到for循环中,然后发布到数据库

时间:2017-10-25 01:28:59

标签: swift firebase

我对快速发展有点新意,遇到了一个问题。我有一个UIImages数组,我正在运行for循环来创建一个URL并使用firebase存储。图像存储在我的firebase存储中,但我目前在创建包含给定图像的URL的帖子时遇到问题。

正确的帖子应包含itemName,itemPrice,username,imageA和imageB。我现在拥有它的方式是它创建2个帖子,我理解,因为它在for循环中,它将为两个图像迭代两次,但是我仍然坚持想要如何在迭代后为两个图像创建一个帖子循环来存储图像。

     @IBAction func confirmAction(_ sender: Any) {

    var uploadedImageUrlsArr = [String]()


    for image in imageArr{
        let imageName = NSUUID().uuidString
        let storageRef = Storage.storage().reference().child("Advertisement_Images_Main").child("\(imageName).png")

        let myImage = image
        guard let uploadData  = UIImagePNGRepresentation(myImage) else {
            return
        }
        storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in

            if let error = error {
                print(error)
                return
            }
            if let imageURL = metadata?.downloadURL()?.absoluteString{
                print (imageURL)
                uploadedImageUrlsArr.append(imageURL)
                let post : [String : AnyObject] = ["item" : self.itemNameTextField.text as AnyObject, "price" : self.itemPriceTextField.text as AnyObject, "username": self.username as AnyObject, "imageA": imageURL as AnyObject]
                self.ref?.child("Items").childByAutoId().setValue(post)

            }



        })
    }

  //  let post : [String : AnyObject] = ["item" : self.itemNameTextField.text as AnyObject, "price" : self.itemPriceTextField.text as AnyObject, "username": self.username as AnyObject, "imageA": imageURL as AnyObject]

    self.performSegue(withIdentifier: "confirmedSegue", sender: nil)
}

1 个答案:

答案 0 :(得分:0)

由于storageRef.putData(...是一个异步调用,所以你需要等待两个图像的响应才能同时发布它们,所以我认为你可以在代码中进行这些更改来实现这种行为你想要的:

        if let imageURL = metadata?.downloadURL()?.absoluteString{
              print (imageURL)
              uploadedImageUrlsArr.append(imageURL)
              if uploadedImageUrlsArr.count == 2 { //you can use self.imageArr.count instead of 2 {
                let post : [String : AnyObject] = ["item" : self.itemNameTextField.text as AnyObject, "price" : self.itemPriceTextField.text as AnyObject, "username": self.username as AnyObject, "imageA": uploadedImageUrlsArr[0] as AnyObject, "imageB": uploadedImageUrlsArr[1] as AnyObject]

                self.ref?.child("Items").childByAutoId().setValue(post)
              }
        }