How to Add a Storage Reference in Swift for Firestore

Firestore how to store reference to document / how to retrieve it?

You're just missing one step. This took me a while to figure out as well.

First, store a variable DocumentReference!

var userRef: DocumentReference!

Then, you want to create a pointer to the document ID — create a DocumentReference from that <- this part you are missing

if let documentRefString = db.collection("users").document(documentId) {
self.userRef = db.document("users/\(documentRefString)")
}

Finally, resume saving your data to the database

db.collection("publications").document().setData([
"author": userRef,
"content": self.uploadedImagesURLs
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}

Hope that helps!

How to upload image to Firestore in swift

At first import FirebaseFirestore.

import FirebaseFirestore

Then you can access the FireStore to first (1) upload the image to the store and afterwards (2) get the URL to access the image.

let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"

let storage = Storage.storage().reference()
storage.child("images").putData(imageV.jpegData(compressionQuality: 0.4), metadata: metadata) { meta, error in
if let error = error {
print(error)
return
}

storage.child(folder).downloadURL { url, error in
if let error = error {
// Handle any errors
print(error)
}
}
}

I like to have an extension of UIImage to do so:

extension UIImage {
func upload(with folder: String, completion: @escaping (URL?) -> Void) {
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"

//let fileName = [UUID().uuidString, String(Date().timeIntervalSince1970)].joined()
let data = self.jpegData(compressionQuality: 0.4)
let storage = Storage.storage().reference()
storage.child(folder).putData(data, metadata: metadata) { meta, error in
if let error = error {
print(error)
completion(nil)
return
}

storage.child(folder).downloadURL { url, error in
if let error = error {
// Handle any errors
print(error)
completion(nil)
}
else {
completion(url)
}
}
}
}
}

Then call it like

imageV.upload(with: "images", completion: { (url: URL?) in
print(url)
}

How to wait till download from Firebase Storage is completed before executing a completion swift

Since loading the image data is an asynchronous operation, any code that needs to run after the images have loaded will need to be inside the completion handler, be called from there, or be otherwise synchronized.

A simple way is to count the number of images that have completely loaded, and call once it matches the length of the array:

imageArray.removeAll()

for imageRef in products! {

let storageRef = self.storage.reference(withPath: imageRef.image!)

storageRef.getData(maxSize: 1 * 1024 * 1024) { [self] data, error in

if let error = error {
print (error)
} else {

//Image Returned Successfully:
let image = UIImage(data: data!)

//Add Images to the Array:
imageArray.append(image!)

// br> if (imageArray.count == products!.count) {
completion (true)
}
}
}
}

Firebase Cloud Firestore - Accessing a collection from a reference

Here's some sample code that shows how to read and print out any of the fields values and also how to read the imageUpload field (an array) and print out the first element's value.

I've included both ways to read data from a document because I believe it answers both parts of the question: how to get the array field imageUpload and then access the first element within that array and how to get the value of the file field within fl_files.

Assuming this points to the correct document:

let docRef = Firestore.firestore().collection("fl_content").document(item.id)

this code will read two fields from the document being pointed to: imageUpload (an array) and fl_id (a String)

docRef.getDocument(completion: { document, error in
if let err = error {
print(err.localizedDescription)
return
}

print( document!.data() ) //for testing to see if we are getting the fields

//how to read an array and access it's elements
let imageUploadArray = document?["imageUpload"] as? Array ?? [""]
if let url = imageUploadArray.first {
print(url)
}

//this is also valid for reading the imageUpload field array
//let anArray = document?.get("imageUpload") as? Array ?? [""]
//if let url = anArray {
// print(url)
//}

//how to read a single field, like file within fl_files
let someId = document?.get("fl_id") as! String //example of reading a field
print(someId)

})

Edit:

It appears the objects stored in the imageUpload array are references not strings. As an example of how to access them... here's the code

let refArray = document?.get("imageUpload") as? [DocumentReference] ?? []
for docRef in refArray {
print(docRef.path) //prints the path to the document at this ref
}


Related Topics



Leave a reply



Submit