我在个人资料图片中添加了点击手势,该图片可以从iPhone
拾取图片
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SignUpVC.handleSelectProfileImgView))
profileImage.isUserInteractionEnabled = true
profileImage.addGestureRecognizer(tapGesture)
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
profileImage.image = pickedImage
selectedImage = pickedImage
}
dismiss(animated: true, completion: nil)
}
此后,我曾尝试将此图片放入 STORAGE ,然后在数据库中获取downloadURL设置
func uploadProfileImage(userUID: String, completion: @escaping (_ url: URL?) -> Void) {
let storageRef = Storage.storage().reference().child("profile_images").child(userUID)
if let imageData = selectedImage.jpegData(compressionQuality: 0.75) {
storageRef.putData(imageData, metadata: nil) { (metadata, error) in
guard metadata != nil else { return }
storageRef.downloadURL(completion: { (url, error) in
guard let url = url else {return}
completion(url)
})
}
}
}
@IBAction func signUpPressed(_ sender: Any) {
Auth.auth().createUser(withEmail: (emailTextField.text!), password: (passwordTextField.text!)) { (result, error) in
if let _eror = error {
print(_eror.localizedDescription )
} else {
let userUID = result?.user.uid
self.uploadProfileImage(userUID: userUID!, completion: { (url) in
guard let url = url else {return}
Database.database().reference().child("users").child(userUID!).setValue(["username":self.usernameTextField.text!, "email":self.emailTextField.text!, "password":self.passwordTextField.text!, "profileImgURL":url])
})
}
}
}
我试图不调用 uploadProfileImage()函数,而只是将值username,email和passsword设置为数据库,它可以工作。但是,当我调用该函数uploadProfileImage()并获取URL时,它将失败。
我检查了存储空间,发现图像已成功上传。这里的问题是我无法获取downloadURL。
请帮助我。非常感谢!
答案 0 :(得分:0)
storageRef.putData(imageData, metadata: nil) { (metadata, error) in
if error != nil {
print("error")
} else {
// your uploaded photo url.
storageRef.downloadURL(completion: { (url, error) in
if error != nil {
print("error")
} else {
print(url!)
}
)}
}
您可以使用此方法并成功完成downloadURL,可以获得下载URL,您可以在浏览器中浏览该URL,以显示上载的图像。