Search code examples
swiftfirebaseuiimageviewuiimagepickercontrollerfirebase-storage

Upload image to Firebase Storage and show as Profile Image


I need help with uploading image to Firebase Storage. I have a profile menu in my app. When user tap on this menu he/she can see profile with their info and Profile Image. So I made it so you can select a photo from the gallery. But I need to save photo to Firebase Storage and add ref to Firebase Database by uid. In addition, the user may not have a photo, so it will be nill because nothing in Database. Look at photo and you will understand everything

extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    var selectedImage: UIImage?
    if let editedImage = info[.editedImage] as? UIImage {
        selectedImage = editedImage
        self.profileImage.image = selectedImage!
        self.savedImage = selectedImage
        picker.dismiss(animated: true, completion: nil)
    } else if let originalImage = info[.originalImage] as? UIImage {
        selectedImage = originalImage
        self.profileImage.image = selectedImage!
        self.savedImage = selectedImage
        picker.dismiss(animated: true, completion: nil)
    }

}



let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView) )
        profileImage.addGestureRecognizer(tapGesture)
        profileImage.isUserInteractionEnabled = true

@objc func handleSelectProfileImageView () {
    print("Tapped")

    let pickerController = UIImagePickerController()
    pickerController.delegate = self
    present(pickerController, animated: true, completion: nil)

}

So, how to upload and dowload image. If the user does not have a photo (ref in Database). He will see image from assets. If the user have photo he will see image from FB. image


Solution

  • For Uploading to Firebase storage

    let imgData: NSData = NSData(data: UIImageJPEGRepresentation((self.img_Photo?.image)!, 0.5)!)
    let _:NSData = NSData(data:UIImagePNGRepresentation(((self.img_Photo?.image)!))!)
    self.uploadProfileImageToFirebase(data: imgData)
    

    Function for uploading

    func uploadProfileImageToFirebase(data:NSData){
        let randomPic = randomString(length: 10)
        let storageRef = Storage.storage().reference().child("Pictures").child("\(value(forKey: "UserUID") ?? randomPic).jpg")
        if data != nil {
            storageRef.putData(data as Data, metadata: nil, completion: { (metadata, error) in
                if(error != nil){
                    print(error)
                    return
                }
                guard let userID = Auth.auth().currentUser?.uid else {
                    return
                }
                // Fetch the download URL
                storageRef.downloadURL { url, error in
                    if let error = error {
                        // Handle any errors
                        if(error != nil){
                            print(error)
                            return
                        }
                    } else {
                        // Get the download URL for 'images/stars.jpg'
    
                        let urlStr:String = (url?.absoluteString) ?? ""
                        let values = ["photo_url": urlStr]
                        self.registerUserIntoDatabaseWithUID(uid: userID, values: values as [String : AnyObject])
                    }
                }
            })
        }
    
    }
    
    func registerUserIntoDatabaseWithUID(uid:String, values:[String:AnyObject]){
        let ref = Database.database().reference(fromURL: "https://domain.firebaseio.com/")
        let usersReference = ref.child("users").child((Auth.auth().currentUser?.uid)!)
    
        usersReference.updateChildValues(values) { (error, ref) in
            if(error != nil){
                print(error)
                return
            }
            self.parentVC?.dismiss(animated: true, completion: nil)
        }
    
    }