user3708224
user3708224

Reputation: 1259

putData method not being executed

I am trying to implement a function to update a users profile picture, which in turn will update (replace) the current picture file in Firebase. For some reason the putData method is not being executed in my function (it does not run the print statement "code got here"). I am not sure why this code is not being run or finishing the function. Thanks in advance!

   // edit profile viewController

        var databaseRef: DatabaseReference!
        var storageRef: StorageReference!

     override func viewDidLoad() {

          databaseRef = Database.database().reference()
          storageRef = Storage.storage().reference()

          loadProfileImage()

     }

     func handleSave() {
     // save profile info to firebase
          updateUsersProfile()
          dismiss(animated: true, completion: nil)
     }

    // update picture func
        func updateUsersProfile(){
            //check to see if the user is logged in
            if let userID = Auth.auth().currentUser?.uid {

                //create an access point for the Firebase storage
                let storageItem = storageRef.child("profile_images").child(userID)

               //get the image uploaded from photo library
                guard let image = profileImageView.image else {return}

                if let newImage = UIImagePNGRepresentation(image) {
                //upload to firebase storage
    // code never executes this putData block ------- ?????
                storageItem.putData(newImage, metadata: nil, completion: { (metadata, error) in
                    print("code got here")
                    if error != nil{
                        print(error!)
                        return
                    }

                    storageItem.downloadURL(completion: { (url, error) in
                        if error != nil{
                            print(error!)
                            return
                        }

                            if let profileImageUrl = metadata?.downloadURL()?.absoluteString {

                                let newValuesForProfile =
                                    ["profileImageUrl": profileImageUrl]

                                //update the firebase database for that user
                                self.databaseRef.child("users").child(userID).updateChildValues(newValuesForProfile, withCompletionBlock: { (error, ref) in
                                    if error != nil{
                                        print(error!)
                                        return
                                    }
                                    print("Profile Successfully Update")
                                }) 
                            }
                        })
                    })
                }
            }
        }

Upvotes: 0

Views: 902

Answers (2)

Tung Dang
Tung Dang

Reputation: 266

I'm using latest Xcode 10.2 and Swift 5. I was searching everywhere for this problem and FINALLY, I CAN FIX IT with this trick: just fix 'FirebaseInstanceID' to version '2.0.0' in the podfile

pod 'Firebase'
pod 'Firebase/Core'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/Storage'
pod 'FirebaseInstanceID', '2.0.0'
pod 'SDWebImage'
#pod 'Firebase/Firestone'
#pod 'Firebase/Messaging'

Then run Terminal and pod install again. Finally, the putData completion handler is executed (even ref.downloadURL completion handler is executed too)

Upvotes: 1

Samuel Chavez
Samuel Chavez

Reputation: 786

if is still useful I had the same issue for a while, the weird part is that it only happened in my computer, when I compiled the app in one of my co-workers computer it all worked just fine, anyway this is what worked for me.

I'm currently using XCode 9.4.1 and Swift 4.0

I used to had the @objc annotation in this two functions:

@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

@objc func imagePickerControllerDidCancel(_ picker: UIImagePickerController) 

I deleted that annotation, and then I set the version of my pods as follows:

pod 'Alamofire'
pod 'ObjectMapper'
pod 'IQKeyboardManagerSwift', '~> 6.0'
pod 'JTAppleCalendar', '7.1.5'
pod 'SwiftPhotoGallery'
pod 'SDWebImage', '~> 4.0'
pod 'Firebase', '~> 5.0'
pod 'Firebase/Auth', '~> 5.0'
pod 'Firebase/Database', '~> 5.0'
pod 'Firebase/Storage'
pod 'Firebase/Messaging'

With that configuration the method finally called the completion and it worked like it does in my co-workers computer.

Finally this is my code inside the didFinishPickingMediaWithInfo function

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    picker.dismiss(animated: true) {
        self.starActivityIndicator()

        // if it's a photo from the library, not an image from the camera
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
        let time = Date.timeIntervalSinceReferenceDate
        let imagePath = self.viewModel.storageRef.child("images/image_\(time * 1000).jpeg")
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpeg"

        if let uploadData = UIImagePNGRepresentation(image.resizedTo1MB()!) {
            imagePath.putData(uploadData, metadata: metadata) { (metadata, error) in
                if let error = error {
                    self.stopActivityIndicator()
                    self.alert(message: "Ocurrió un error al enviar la imagen", title: "Error")
                    print("Error uploading: \(error.localizedDescription)")
                    return
                }

                imagePath.downloadURL(completion: { (url, error) in
                    if let error = error {
                        self.stopActivityIndicator()
                        self.alert(message: "Ocurrió un error al enviar la imagen", title: "Error")
                        print("Error getting url: \(error.localizedDescription)")
                        return
                    }

                    guard let url = url else { return }
                    self.stopActivityIndicator()
                })
            }
        }
    }
}

Let me know if you have any questions.

Upvotes: 0

Related Questions