正在将图片链接上传到swifui的firestore



我正试图将图像上传到firebaseStorage,并在swiftui中的买卖应用程序中获取该图像的链接

这是我写的主要功能

func uploadPhoto() {

// Make sure that the selected image poperty isn't nil
guard selectedImage != nil else{
return
}
let storageRef = Storage.storage().reference()

//Turn our image into data
let imageData = selectedImage!.jpegData(compressionQuality: 0.8)

guard imageData != nil else {
return
}

// Specify the file path an name
let path = "images/(UUID().uuidString).jpg"
let fileRef = storageRef.child(path)

// Upload that data
let uploadTask = fileRef.putData(imageData!) { metadata, error in
if error == nil && metadata != nil {

fileRef.downloadURL { url, error in
guard let url = url, error == nil else {
return
}
let urlString = url.absoluteString
print("Download url: (urlString)")
self.imageUrl = urlString
let firestoreRef = Firestore.firestore()
firestoreRef.collection("users").document().setData(["items": urlString])

}

}
}
}

这是我的addData函数:

// Add data
func addData(items: Items) {
if let currentUser = currentUser {
do {
try db.collection("users").document(currentUser.uid).updateData(["items": FieldValue.arrayUnion([Firestore.Encoder().encode(items)])])
} catch {
print("Error occured retriving data")
}
}
}

但问题是,当我试图上传/引用firestore上的图片链接时,它不起作用。

我是这样寄的这是**型号**

struct UserData: Codable, Identifiable {
@DocumentID var id: String?
var items: [Items]

}
struct Items: Codable, Identifiable {
var id = UUID()
var title: String
var price: String
var description: String
var image: String?
}

这是我发送的方式

VStack (spacing: 25){
Button {
if selectedImage != nil {
uploadPhoto()
}
if title != "" && price != "" && description != ""  {
viewModel.addData(items: Items(title: title, price: price, description: description,   image: imageUrl))
}

} label: {
Text("Publish").font(.buttonTitle)
}.buttonStyle(CustomButton())
}

我试着像上面描述的那样发送,但我收到了这个。在此处输入图像描述

每次通话都会收到一份新文档的原因是

firestoreRef.collection("users").document().setData(["items": urlString])

每次调用不带任何参数的document()时,它都会生成一个新文档。为了防止这种情况,您需要在document()调用中传递UID,在本例中传递用户的UID,就像您在调用updateData:db.collection("users").document(currentUser.uid)的调用中所做的那样。

如此组合:

firestoreRef.collection("users").document(currentUser.uid).setData(["items": urlString])

最新更新