Firebase图片对象不存在?

时间:2018-01-02 02:47:34

标签: ios firebase uiimage firebase-storage

我目前正在学习如何向/从Firebase上传/下载图像。但是,我遇到了两个问题:

  1. 当我将图片上传到我的Firebase控制台时,它说它的类型是" application / octet-stream"这不是我想要的(我上传了一个jpeg文件)
  2. 以下是代码:

    @IBAction func completeSignUpButton(_ sender: UIButton) {
        let userProfileImageRef = storage.child("userProfileImage")
    
        //UPloading the photo into firebase
        let data = Data()
        //uploading user profile picture
        if self.userInitialPhoto.image != nil {
            if let uploadData = UIImagePNGRepresentation(self.userInitialPhoto.image!) {
                userProfileImageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
    
                    if error != nil {
                        print(error?.localizedDescription)
                        return
                    } else {
                        print("Image upload success!")
                        //self.dismiss(animated: true, completion: nil)
                        self.performSegue(withIdentifier: "completeRegistrationSegue", sender: self)
                    }
                })
    
            }
    
        } else {
            print("You need to pick a picture!")
    
        }
    
    }
    

    所以这可能是造成我第二个问题的问题:

    1. 当我尝试在我的应用中将图像从Firebase加载到我的UIImage时,会显示对象可选(\" userID \")/ userProfileImage不存在。"
    2. 这是我的代码:

       override func viewDidLoad() {
          super.viewDidLoad()
          // Do any additional setup after loading the view.
          docRef = Firestore.firestore().collection("user Status").document("Current Status")
          self.userStatusTableView.reloadData()
          let referencePath = Storage.storage().reference(withPath: "\(userID)/userProfileImage")
          let userProfileImageRef = Storage.storage().reference().child("\(userID)/userProfileImage")
          userProfileImageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
              if error != nil {
                  print("There's an eror downloading the image\(error?.localizedDescription)")
              } else {
                  self.userProfileImage.image = UIImage(data: data!)
              }
          }
      }
      

      我想知道如何解决这些问题。

      感谢您的帮助,祝大家新年快乐。

1 个答案:

答案 0 :(得分:0)

将图片上传到firebase时,您将元数据传递为nil。你需要在那里传递图像元数据

let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"

并在上传complitionBlock中,您可以使用

获取该图片的网址
if error == nil , let meta = meta {
     if let url = meta.downloadURL()?.absoluteString {
           //use this url to access your image
     }
}