Created
May 20, 2020 18:09
-
-
Save OmarJalil/50854e96fa4af4aa6896381679d08b84 to your computer and use it in GitHub Desktop.
ImageManager for Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class ImageManager { | |
/// Saves an image with an Id | |
public static func saveImage(imageName: String, image: UIImage) { | |
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } | |
let fileName = imageName | |
let fileURL = documentsDirectory.appendingPathComponent(fileName) | |
guard let data = image.jpegData(compressionQuality: 1) else { return } | |
/// Verifies if it exists already and deletes it if so | |
if FileManager.default.fileExists(atPath: fileURL.path) { | |
do { | |
try FileManager.default.removeItem(atPath: fileURL.path) | |
print("Removed old image") | |
} catch let removeError { | |
print("couldn't remove file at path", removeError) | |
} | |
} | |
do { | |
try data.write(to: fileURL) | |
} catch let error { | |
print("error saving file with error", error) | |
} | |
} | |
/// Loads the image with an Id | |
public static func loadImageFromDiskWith(fileName: String) -> UIImage? { | |
let documentDirectory = FileManager.SearchPathDirectory.documentDirectory | |
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask | |
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true) | |
if let dirPath = paths.first { | |
let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName) | |
let image = UIImage(contentsOfFile: imageUrl.path) | |
return image | |
} | |
return nil | |
} | |
public static func deleteImageFromDisk(named imageName: String) { | |
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } | |
let fileName = imageName | |
let fileURL = documentsDirectory.appendingPathComponent(fileName) | |
/// Verifies if it exists already and deletes it if so | |
if FileManager.default.fileExists(atPath: fileURL.path) { | |
do { | |
try FileManager.default.removeItem(atPath: fileURL.path) | |
print("Removed old image") | |
} catch let removeError { | |
print("couldn't remove file at path", removeError) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment