skip to Main Content

The user can select a picture as a profile picture in my app.
After that he can click on done and the picture gets uploaded.
If the user does not select a picture my code still upload a blank picture by clicking on done.

How can I check if the user selected a picture and then trigger the function?
I need an if else statement but don’t know how to get the status "is a picture selected?"

I could maybe also use a default value. But that would mean to download the actual picture and reupload it again as default. That does not sound good.

@IBOutlet weak var tapToChangeProfileButton: UIButton!
    var imagePicker: UIImagePickerController!
    var ref: DatabaseReference!
    
    @IBAction func updateProfile(_ sender: UIButton) {
               
        uploadPic(arg: true, completion: { (success) -> Void in
               if success {
                   addUrlToFirebaseProfile()
               } else {
               }
           })
        
        
        func uploadPic(arg: Bool, completion: @escaping (Bool) -> ()) {
            
            guard let imageSelected = self.image else {
                completion(false);
                return
                
            }
            guard let imageData = imageSelected.jpegData(compressionQuality: 0.1) else {
                completion(false);
                return
                
            }
            let storageRef = Storage.storage().reference(forURL: "gs://....e.appspot.com")
            let storageProfileRef = storageRef.child("profilePictures").child(Auth.auth().currentUser!.uid)
            let metadata = StorageMetadata()
            metadata.contentType = "image/jpg"
            storageProfileRef.putData(imageData, metadata: metadata, completion: {
                (storageMetadata, error) in
                if error != nil {
                    //print(error?.localizedDescription)
                    completion(false);
                    return
                }
                storageProfileRef.downloadURL(completion: { (url, error) in
                    if let metaImageURL = url?.absoluteString {
                        print(metaImageURL)
                        self.urltoPicture = metaImageURL
                        completion(true)
                    }
                    else
                    {
                        completion(false); return
                    }
                })
            })
            
        }
        
        func addUrlToFirebaseProfile(){
            ref = Database.database().reference()
            let userID = Auth.auth().currentUser!.uid
            ref.child("user/(userID)").updateChildValues(["profileText": profileText.text!])
            print(urltoPicture)
            ref.child("user/(userID)").updateChildValues(["picture": urltoPicture])
        }
                                                       
        self.navigationController?.popViewController(animated: true)
    }
    
   override func viewDidLoad() {
        
        super.viewDidLoad()
        let imageTap = UITapGestureRecognizer(target: self, action: #selector(openImagePicker))
        profileImageView.isUserInteractionEnabled = true
        profileImageView.addGestureRecognizer(imageTap)
        tapToChangeProfileButton.addTarget(self, action: #selector(openImagePicker), for: .touchUpInside)
        
        imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = true
        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self
}

 @objc func openImagePicker(_ sender:Any){
        self.present(imagePicker, animated: true, completion: nil)
    }

extension ImagePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
        picker.dismiss(animated: true, completion: nil)
    }
    
    internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any])
    {
        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            self.profileImageView.image = pickedImage
            
            image = pickedImage
        }
        picker.dismiss(animated: true, completion: nil)
    }
}

2

Answers


  1. You are setting self.image if the user selects a photo.

    But you are not unsetting self.image if the user doesn’t select a photo. It needs to be set to nil (not to an empty UIImage()).

    Login or Signup to reply.
  2. As I see from your code, whenever you get an image from imagePickerController you store it into variable self.image. Then whenever you click Done you just upload this self.image

    Make variable self.image can be nil then remember to unset it after uploading successfully

    Code will be like this

    var image : UIImage? = nil
    
    @IBAction func updateProfile(_ sender: UIButton) {
        uploadPic(arg: true, completion: { (success) -> Void in
            if success {
                addUrlToFirebaseProfile()
                self.image = nil // reset image to nil if success
            } else {
            }
        })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search