gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:03:33 25 4
gpt4 key购买 nike

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

正确的帖子应包含 itemName、itemPrice、用户名、imageA 和 imageB。我现在的方式是它创建了 2 个帖子,我理解它是因为它在 for 循环中,并且它将对两个图像迭代两次,但是我一直在思考如何在迭代 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)
}

最佳答案

由于 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)
}
}

关于swift - 在for循环中附加图像url数组,然后发布到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com