我正在尝试将图像从ImageView升级到Firebase存储,但是它不起作用。
我在下面列出了我的代码:我的图像视图称为ProfileImage
let storageRef = Storage.storage().reference().child("myImage.png")
if let uploadData = self.ProfileImage.image!.pngData() {
storageRef.putFile(from: uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("error")
completion(nil)
} else {
// your uploaded photo url.
}
}
}
出现错误“无法将类型为“数据”的值转换为预期的组合类型为“ URL”
答案 0 :(得分:1)
您正在尝试上传数据,而不是文件。替换
putFile
使用
putData
它应该可以正常工作
答案 1 :(得分:0)
尝试此代码:-
let storageRef = Storage.storage().reference().child("myImage.png")
if let uploadData = UIImagePNGRepresentation(self.profileImage.image!) {
storageRef.put(uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("\(error.localizeDescription)")
} else {
// your uploaded photo url.
}
}
答案 2 :(得分:0)
let refDatabase = Database.database().reference()
var refstorage = Storage.storage().reference()
let data = image.jpegData(compressionQuality: 1.0) //
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
let postkey = refDatabase.child("Post").childByAutoId().key
print(postkey)
let imagename = "PostImage/\(postkey).png"
refstorage = refstorage.child(imagename)
let timestamp = Date().timeIntervalSince1970 // you can use this to track time when it was uploaded.
self.refstorage?.putData(data!, metadata: metadata, completion: { (meta, error) in
if error == nil{
if let imageData = meta?.downloadURL()?.absoluteString{
// DO SOMETHING
} else {
print("Couldn't get the URL for image")
}
}
})
答案 3 :(得分:0)
我知道已经回答了这个问题,但是有一种更简单的方法可以解决此问题。除了导入Firebase和Firebase存储,您还必须将FirebaseUI添加到您的Podfile中并进行导入。
完成此操作后,您可以更轻松地将图像添加到应用程序中。
let storage = Storage.storage()
let storageRef = storage.reference()
let placeholderImage = UIImage(named: "placeholder.jpeg")
let reference = storageRef.child("myImage.png")
ProfileImage.sd_setImage(with: reference, placeholderImage: placholderImage)
(占位符图像只是您在XCode中放置在资产文件夹中的透明图像,可以在应用程序中多次重复使用,以备您需要在应用程序上获取Firebase图像时使用。)