Reputation:
I have been using the firebase guides to upload a user image to firebase storage but after I upload the user image nothing appears in the folder. How do I solve this problem to successfully upload my image to firebase storage is there anything i'm missing ?
Size 0 bytes
let storage = Storage.storage()
let storageRef = storage.reference()
let image = UIImage(named: "ProfileImage")
let data = Data()
let starsRef = storageRef.child("ProfileImage.jpeg")
let metadata = StorageMetadata()
metadata.contentType = "ProfileImage/jpeg"
let uploadTask = starsRef.putData(data, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
return
}
let size = metadata.size
starsRef.downloadURL { (url, error) in
guard let downloadURL = url else {
return
}
}
}
Upvotes: 1
Views: 1520
Reputation: 536
Here is 6 steps on how to upload the image to Firebase Storage and retrieve the URL path for later usage.
UUID().uuidString
compressionQuality
Convert the URL to url?.absoluteString
and print it out using print
//1. Create an unique name for your image
let imageName = UUID().uuidString
let imageReference = Storage.storage().reference().child(imageName)
//2. Compress quality
if let uploadData = self.tempImageView.image!.jpegData(compressionQuality: 0.5){
//3. Save image as .jpeg
let metaDataForImage = StorageMetadata()
metaDataForImage.contentType = "image/jpeg"
//4. Add the data to Firebase Storage
imageReference.putData(uploadData, metadata: metaDataForImage) { (meta, err) in
if let err = err{
print(err.localizedDescription)
}
else{
//5. Retrieving the image URL
imageReference.downloadURL { (url, err) in
if let err = err{
print(err.localizedDescription)
}
else{
//6. Print the complete URL as string
let urlString = url?.absoluteString
print(urlString)
}
}
}
}
}
Upvotes: 1
Reputation: 18428
contentType
should be image/jpeg
. I googled some piece codes, it shows the same concept.contentType
, more detail at this wiki link.jpeg
binary. But data = image.pngData()
, it seems to be the binary data of png
. // data is `png` binary
let data = image.pngData()
// imageData is `jpeg` binary
let imageData = image.jpegData(compressionQuality: 0.9)
let uiImage: UIImage = UIImage(data: imageData!)!
let starsRef = storageRef.child("ProfileImage.jpg")
let metadata = StorageMetadata()
// About contentType
// See it: https://en.wikipedia.org/?title=Content_type&redirect=no
metadata.contentType = "ProfileImage/jpeg"
// data is `png` binary, but contentType is `jpeg` ?
let uploadTask = starsRef.putData(data!, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
return
}
Upvotes: 0
Reputation: 91
Make that let data
a guard let data
, that way you won't have to force-unwrap when you need it to be non-optional. I'd say generally avoid force-unwrapping in general.
Upvotes: 0