Swift 3 xCode 8.2
Получение справочника документов:
func getDocumentDirectoryPath() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory as NSString
}
Сохранение:
func saveImageToDocumentsDirectory(image: UIImage, withName: String) -> String? {
if let data = UIImagePNGRepresentation(image) {
let dirPath = getDocumentDirectoryPath()
let imageFileUrl = URL(fileURLWithPath: dirPath.appendingPathComponent(withName) as String)
do {
try data.write(to: imageFileUrl)
print("Successfully saved image at path: \(imageFileUrl)")
return imageFileUrl.absoluteString
} catch {
print("Error saving image: \(error)")
}
}
return nil
}
Загрузка:
func loadImageFromDocumentsDirectory(imageName: String) -> UIImage? {
let tempDirPath = getDocumentDirectoryPath()
let imageFilePath = tempDirPath.appendingPathComponent(imageName)
return UIImage(contentsOfFile:imageFilePath)
}
Пример:
//TODO: pass your image to the actual method call here:
let pathToSavedImage = saveImageToDocumentsDirectory(image: imageToSave, withName: "imageName.png")
if (pathToSavedImage == nil) {
print("Failed to save image")
}
let image = loadImageFromDocumentsDirectory(imageName: "imageName.png")
if image == nil {
print ("Failed to load image")
}