从UIImagePicker将图像上传到Firebase

时间:2019-06-01 14:36:05

标签: swift firebase uiimage uiimagepickercontroller

选择UIImage选择器后,我想将个人资料图片上传到Firebase。但是我不知道该怎么做 我无法理解文档,因为我是编码新手。请帮我。我需要将图片上传到Firebase。这将是用户图片,因此对图片的引用应保存到数据库。

extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {




    let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
    profileImage.image = image
   picker.dismiss(animated: true, completion: nil)
}

我不上传和下载个人资料图片。

1 个答案:

答案 0 :(得分:1)

创建存储引用并添加文件夹名称和图像名称。

Storage.storage().reference().child("id").child("profile.png")

并使用putData:metadata:completion:方法上传图片。图片上传后,获取图片网址并在用户详细信息中进行更新。

上传个人资料图片

import FirebaseStorage
import FirebaseAuth

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage, let imageData = image.pngData() {
        profileImage.image = image
        let storageRef = Storage.storage().reference().child("id").child("profile.png")
        let metaData = StorageMetadata()
        metaData.contentType = "image/png"
        storageRef.putData(imageData, metadata: metaData) { (metaData, error) in
            if error == nil, metaData != nil {
                storageRef.downloadURL { url, error in
                    if let url = url {
                        print(url)//URL of the profile image
                        self.saveProfileImageUrlInUserDetails(url: url)
                    }
                }
            } else {
                print(error?.localizedDescription)//upload failed
            }
        }
    }
    picker.dismiss(animated: true, completion: nil)
}

保存用户详细信息中上传的照片参考 Update a user's profile

func saveProfileImageUrlInUserDetails(url: URL) {
    let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
    changeRequest?.photoURL = url
    changeRequest?.commitChanges(completion: { error in
        if error == nil {
            //saved
        } else {
            print(error?.localizedDescription)//failed to udpate
        }
    })
}

下载个人资料图片

if let profileImgUrl = Auth.auth().currentUser?.photoURL?.absoluteString {
    let ref = Storage.storage().reference(forURL: profileImgUrl)
    ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
        if let error = error {
            print(error.localizedDescription)
        } else if let data = data, let image = UIImage(data: data) {
                self.profileImage.image = image
        }
    }
}