putData方法没有被执行

时间:2017-06-23 20:42:36

标签: swift firebase-realtime-database save firebase-storage imageurl

我正在尝试实现一个更新用户个人资料图片的功能,而这个功能又会更新(替换)Firebase中的当前图片文件。由于某种原因,putData方法没有在我的函数中执行(它不运行print语句"代码到达这里")。我不确定为什么这个代码没有运行或完成该功能。提前谢谢!

   // 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")
                                }) 
                            }
                        })
                    })
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

我正在使用最新的Xcode 10.2和Swift 5。 我到处都在寻找这个问题,最后,我可以用这个技巧来修复它:只需将podfile中的'FirebaseInstanceID'修复为版本'2.0.0'

+

然后再次运行Terminal and pod install。 最后,执行putData完成处理程序(甚至也执行ref.downloadURL完成处理程序)

答案 1 :(得分:0)

如果仍然有用,我会在一段时间内遇到相同的问题,那么奇怪的部分是它仅发生在我的计算机上,当我在自己的一台同事计算机上编译该应用程序时,一切都很好,无论如何什么对我有用。

我当前正在使用XCode 9.4.1和Swift 4.0

我曾经在这两个函数中使用@objc批注:

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

@objc func imagePickerControllerDidCancel(_ picker: UIImagePickerController) 

我删除了该注释,然后按如下所示设置了广告连播的版本:

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'

通过这种配置,该方法最终称为完成,并且其工作方式与我的同事计算机中的工作相同。

最后这是我在 didFinishPickingMediaWithInfo 函数中的代码

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()
                })
            }
        }
    }
}

如果您有任何疑问,请告诉我。