我遇到的麻烦是在firebase中创建一个uiimageurl字符串的常量。我将网址存储在了Firebase数据库中。看起来像这样:
在早期版本的firebase和swift中,您可以通过执行以下操作来做到这一点:
let imageUrl = User.profileImageUrl
现在这不起作用,我需要找到有关如何执行此操作的更新版本。非常感谢您的回答,非常感谢!
您需要先保存图像。然后,您将能够获取保存图像的URL。这是一个例子。
func saveButtonPressed() {
let storageRef = Storage.storage().reference(withPath: "profile_images")
let imageData = profileImageView.image?.jpegData(compressionQuality: 0.8)
guard let data = imageData else { return }
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
// Here you can decide where to save the image. In your case it will look something like this.
// let ref = Storage.storage().reference(withPath: "profile_images").child(user.uid)
storageRef.putData(data, metadata: metadata) { (metadata, error) in
if let _ = error {
// Error Handling...
return
}
storageRef.downloadURL { (url, error) in
if let _ = error {
// Error Handling...
return
}
guard let url = url else { return }
let urlString = url.absoluteString
print(urlString)
}
}
}
希望这会有所帮助。
因此,如果要获取已保存在存储器中的图像的URL。您首先需要找到它的引用。
//Example as above
let storageRef = Storage.storage().reference(withPath: "profile_images").child(user.uid)
storageRef.downloadURL { (url, error) in
if let _ = error {
// Error Handling...
return
}
guard let url = url else { return }
let urlString = url.absoluteString
print(urlString)
}
如果参考中没有图像,则会出现错误。它基本上与我提供的第一个答案相同,但是没有节省。由于图像已经存在,您可以仅使用ref.downloadURL。希望这会有所帮助。
另外,要从Firebase填充图像,我使用了它,这听起来像对您有用...
func showProfilePicture() {
if let uid = Auth.auth().currentUser?.uid {
let storage = Storage.storage()
let storageRef =
storage.reference(withPath: "\(uid)/photos/\(0)")
PhotoUploader.downloadImageUrl(from:
storageRef) {[weak self] (url) in
guard let url = url else { return }
self?.displayProfileImage.downloaded(from: url, contentMode: .scaleAspectFill)
}
} else {
showAlert(withTitle: "Error", message: "Not signed in")
}
}