如何在CoreData中添加图像以及如何在CoreData中保存图像

时间:2018-04-10 11:30:23

标签: swift core-data

如何在核心数据中添加图像?图像类型我选择了什么。以及如何保存核心数据图像。如何添加图像?

1 个答案:

答案 0 :(得分:0)

步骤1: - 将图像保存在文档目录

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
    let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
    let newPath = path.appendingPathComponent("image.jpg") //Possibly you Can pass the dynamic name here
    // Save this name in core Data using you code as a String.
    let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
    do {
        try jpgImageData!.write(to: newPath)
    } catch {
        print(error)
    }
}}

步骤:-2:从文档目录中取回图像,并在表格视图单元格中逐行显示索引路径。

let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath          = paths.first
    {
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image.png") //Pass the image name fetched from core data here
        let image    = UIImage(contentsOfFile: imageURL.path)
        cell.imageView.image = image
}

这是一个简单而方便的方法