如何在iPhone设备存储中保存/读取图像?

时间:2017-06-15 04:00:50

标签: swift

我要将图像保存到iphone设备中并从中读取。 所以我为这个函数写了这样的文字。

/*
 *  save image to local device
 */
func saveImageToLocal(image: UIImage, fileName: String) {
    if let data = UIImagePNGRepresentation(image) {
        let filePath = self.getDocumentsDirectory().appendingPathComponent(fileName)
        try? data.write(to: filePath, options: .atomic)
    }
}

/*
 *  get image from local device
 */
func getImageFromLocal(fileName:String) -> UIImage? {
    if let filePath = "\(self.getDocumentsDirectory())\(fileName)" as String! {
        if let image = UIImage(contentsOfFile: filePath) {
            return image
        }
    }
    return nil
}

/*
 *  get document directory to save/read local file
 */
func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

但它无法正常工作。 我有什么错误? 我该如何实现呢? 问候。

1 个答案:

答案 0 :(得分:0)

filePath方法中获取getImageFromLocal(fileName:) -> UIImage?时遇到问题。根据您的saveImageToLocal(image:)方法进行更改,如下所示:

func getImageFromLocal(fileName:String) -> UIImage? {
    let filePath = self.getDocumentsDirectory().appendingPathComponent(fileName)
    if let image = UIImage(contentsOfFile: filePath.path) {
        return image
    }
    return nil
}