[我的个人资料图像上传到Firebase存储时,没有照片出现,但是我的代码中没有错误,如何解决此问题,以将我的用户个人资料图像正确上传到Firebase存储?
let uid = user.uid
let storageRef = Storage.storage().reference(forURL: "gs://tvmassmedianetwork.appspot.com").child("profile_Image").child(uid)
if let ProfileImge = self.SelectedImage, let imagedata = ProfileImge.jpegData(compressionQuality: 0.1) {
storageRef.putData(imagedata, metadata: nil) { (metadata, error) in
if error != nil {
return
}
let ProfileImageUrl = metadata?.storageReference?.downloadURL(completion: )
let ref = Database.database().reference()
let UsersReference = ref.child("users").child(user.uid)
let newUsersReference = UsersReference.child(uid)
newUsersReference.setValue(["username": self.UsernameTextField.text ?? "" as Any, "email": self.EmailTextField.text ?? "", "ProfileImageUrl": ProfileImageUrl ?? ""])
}
}
func uploadImage(withId id: String) {
guard let imageData = self.SelectedImage?.jpegData(compressionQuality: 0.7) else { return }
Storage.storage().reference(withPath: "usersImages/\(id).jpg").putData(imageData, metadata: nil) { (metaData, error) in
if error == nil{
print("Image has been uploaded!")
}
}
}
获取downloadURL
需要调用服务器,因此是异步操作。下载URL仅在可以传递到downloadURL
方法的闭包中可用。
因此您可以使用类似的方法将其放入数据库:
metadata?.storageReference?.downloadURL( url, error in
if let error = error {
// Handle any errors
} else {
let ref = Database.database().reference()
let UsersReference = ref.child("users").child(user.uid)
let newUsersReference = UsersReference.child(uid)
newUsersReference.setValue(["username": self.UsernameTextField.text ?? "" as Any, "email": self.EmailTextField.text ?? "", "ProfileImageUrl": url ?? ""])
}
}
我认为此代码段看起来也很奇怪:
let UsersReference = ref.child("users").child(user.uid)
let newUsersReference = UsersReference.child(uid)
它可能应该是:
let UsersReference = ref.child("users")
let newUsersReference = UsersReference.child(uid)
另请参阅: