Reputation:
I added a tap gesture to profile image that picks images from 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)
}
I have tried to put this image to STORAGE afterwards and then get the downloadURL to set in the database
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])
})
}
}
}
I tried not to invoke uploadProfileImage() function and just set the values username, email and passsword to database, it works. However, when I call that function uploadProfileImage() and get the URL, it fails.
I have checked the storage and found that the image is successfully uploaded. The problem here is that I fail to get the downloadURL.
Please help me. Thanks so much!
Upvotes: 0
Views: 196
Reputation: 105
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!)
}
)}
}
You can use this methods and success of the downloadURL you can get your download url that you can browse in your browser that show your uploaded image.
Upvotes: 1