我一直在使用Firebase指南将用户图像上传到Firebase存储,但是在上传用户图像后,文件夹中没有任何内容。如何解决此问题,以成功将图像上传到Firebase存储中,我还缺少什么?
大小0字节
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
}
}
}
答案 0 :(得分:1)
关于将图像上传到Firebase存储并检索URL路径以供以后使用的步骤,这里有6个步骤。
UUID().uuidString
compressionQuality
将URL转换为url?.absoluteString
并使用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)
}
}
}
}
}
答案 1 :(得分:0)
将let data
设为guard let data
,这样一来,当您需要非可选选项时,就不必强行拆包。我说一般来说通常避免用力展开。
答案 2 :(得分:0)
contentType
应该是image/jpeg
。我googled some piece codes,它显示了相同的概念。contentType
,more detail at this wiki link。jpeg
二进制文件。但是data = image.pngData()
似乎是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
}