Firebase存储:上传的图像未保存在应用中

时间:2017-04-08 11:29:28

标签: firebase swift3 xcode8 firebase-storage

我通过.Camera将图像上传到Firebase存储。当我关闭应用程序并再次运行时,此图像不会保存在我的应用程序中。我知道我错过了什么。请告诉我应该添加什么。非常感谢! 这是我的代码:

import UIKit
import Firebase
import FirebaseStorage

class PicturesOfCoinsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBAction func saveButton(_ sender: UIButton) {
        saveOneEuroCentImage()
    }

    @IBOutlet weak var oneEuroCentImage: UIImageView!

    @IBAction func usePhotoButton(_ sender: UIButton) {

        let picker = UIImagePickerController()
        picker.sourceType = .camera
        self.present(picker, animated: true, completion: nil)
        picker.delegate = self
    }

    func saveOneEuroCentImage() {

        let storageRef = FIRStorage.storage().reference().child("userPictures/oneEuroCent.jpg")

        if let uploadData = UIImagePNGRepresentation(self.oneEuroCentImage.image!) {

            storageRef.put(uploadData, metadata: nil) {(metadata, error) in

                if error != nil {
                    print(error)
                    return
                }
            }
        }
    }

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        oneEuroCentImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        picker.dismiss(animated: true, completion: nil)
    }
}

enter image description here

1 个答案:

答案 0 :(得分:0)

如果您想在应用上拥有图像的永久副本,则必须在上传之前将照片保存到应用文档目录。从上面的代码中,您只需将其上传到firebase中的云存储,但没有用于在本地保存图片的代码,这就是为什么在再次运行应用程序时它不存在的原因。 我建议您为图像创建文档目录文件路径或URL,然后保存它。

  let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let path = paths.first
let imageFolderPath = path?.appending("MyFBImages")
if !FileManager.default.fileExists(atPath: imageFolderPath!){
    do {
        try FileManager.default.createDirectory(atPath: imageFolderPath!, withIntermediateDirectories: true, attributes: [:])
    } catch let error {
        print(error.localizedDescription)
    }
}
let imageFilePath = imageFolderPath?.appending("myImageName.jpg")
let imageData = UIImageJPEGRepresentation(UIImage(), 1)
do {
    try imageData?.write(to: URL(fileURLWithPath: imageFilePath!))
} catch let error {
     print(error.localizedDescription)
}

N / B:您可以从上传到firebase之前创建的图像中获取代码中的imageData。 这应该可以帮助您在本地保存图像。下次运行应用程序时,您可以通过从保存已保存照片的网址内容初始化UIImage来访问以前的图像。 我希望这会帮助你。