Firebase更改photoURL

时间:2018-01-10 08:56:14

标签: ios swift firebase firebase-authentication

当用户点击他们的个人资料照片时,他们可以选择新照片。我希望将照片存储到我的存储和数据库中,并在imagePickerController被取消后立即更新视图,新图像显示在屏幕上,但数据库中没有任何变化,登录和退出旧的配置文件图像后仍然存在。

enter image description here

var user: User!

var dataBaseRef: DatabaseReference!{
    return Database.database().reference()
}
var storageRef: StorageReference!{
    return Storage.storage().reference()
}

func updatePhoto() {
    let user = Auth.auth().currentUser
    let newPhoto = profileImage.image

    let imgData = UIImageJPEGRepresentation(newPhoto!, 0.7)!
    let imagePath = "profileImage\(user.uid)/userPic.jpg"
    let imageRef =  storageRef.child(imagePath)
    let metadata = StorageMetadata()
    metadata.contentType = "image/jpeg"
    imageRef.putData(imgData, metadata: metadata) { (metadata, error) in
        if error == nil {
    let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()

            if let photoURL = metadata!.downloadURL(){

                changeRequest?.photoURL = photoURL
            }

            changeRequest?.commitChanges(completion: { (error) in
        if error == nil{

            let user = Auth.auth().currentUser

            let userInfo = ["firstLastName": self.nameOld,  "email": self.emailString, "password": self.passwordOld, "location": self.locationOld, "interests": self.interestsOld, "biography": self.bioOld, "uid": self.uid, "photoURL": String(describing: user?.photoURL!)]

            let userRef = self.dataBaseRef.child("users").child((user?.uid)!)
            userRef.setValue(userInfo)
            let credential = EmailAuthProvider.credential(withEmail: self.emailString, password: self.passwordOld)

                    user?.reauthenticate(with: credential) { error in
                        if let error = error {

                            print(error)
                            // An error happened.
                        } else {
                            print("AUTHENTICATED")
                            // User re-authenticated.
                        }
                    }
            print("user info set")

        }

    })
        }}}



func loadUserInfo(){


    let userRef = dataBaseRef.child("users/\(Auth.auth().currentUser!.uid)")

    userRef.observe(.value, with: { (snapshot) in

        let user = Users(snapshot: snapshot)

        if let username = user.firstLastName{
            self.name.text = username
            self.nameOld = username
        }


        if let userLocation = user.location{
            self.location.text = userLocation
            self.locationOld = userLocation
        }
        if let bio = user.biography{
            self.biog.text = bio
            self.bioOld = bio
        }
        if let interests = user.interests{
            self.interests.text = interests
            self.interestsOld = interests 
        }

        if let imageOld = user.photoURL{


            //  let imageURL = user.photoURL!



            self.storageR.reference(forURL: imageOld).getData(maxSize: 10 * 1024 * 1024, completion: { (imgData, error) in

                if error == nil {
                    DispatchQueue.main.async {
                        if let data = imgData {
                            self.profileImage.image = UIImage(data: data)
                        }
                    }

                }else {
                    print(error!.localizedDescription)

                }

            }


            )}


    }) { (error) in
        print(error.localizedDescription)
    }


}

override func viewDidLoad() {
    super.viewDidLoad()
    setGestureRecognizersToDismissKeyboard()
    loadUserInfo()
}



   func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage]  as? UIImage{
        self.profileImage.image = image
        updatePhoto()
    }
    else if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
        self.profileImage.image = image
        updatePhoto()
    }
    self.dismiss(animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:0)

From apple documentation,UIImagePickerControllerEditedImage:指定用户编辑的图像和UIImagePickerControllerOriginalImage:指定用户选择的原始未剪切图像。 如果用户未编辑所选图像,您还应调用updatePhoto()功能以上传所选照片:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage]  as? UIImage{
        self.profileImage.image = image
        updatePhoto()
    }
    else if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
        self.profileImage.image = image
        updatePhoto()
    }
    self.dismiss(animated: true, completion: nil)
}