将图像保存到文件系统

时间:2017-05-20 13:06:45

标签: ios swift3 xcode8

在main.storyboard我有UIImageView和按钮。我想保存我通过相机到文件系统的图像。但是当我再次加载我的应用程序时,此图像消失了。请告诉我,我做错了什么? 这是我的代码:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {


    @IBAction func useCamera(_ sender: UIButton) {

        let picker = UIImagePickerController()
        picker.sourceType = .camera

        self.present(picker, animated: true, completion: nil)
        picker.delegate = self
    }

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

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

        imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        picker.dismiss(animated: true, completion: nil)

        if imageView.image == UIImage(named: "example.jpg") {
            if let data = UIImageJPEGRepresentation(imageView.image!, 0.8) {
                let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
                try? data.write(to: filename)
            }
        }
    }

    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }
}

1 个答案:

答案 0 :(得分:0)

你究竟做错了什么,我不知道。我还没有测试过您的代码。这是一个可以正常工作的保存程序。它在当前位于应用商店中的应用上进行测试。

func save(image: UIImage, with fileName: String, and imageName: String?) {

    let documentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first
    let imageStore = documentsDirectory?.appendingPathComponent(fileName)
    let imageData = UIImagePNGRepresentation(image)

    do {
        try imageData?.write(to: imageStore!)
    } catch {
        print("Couldn't write the image to disk.")
    }
}