Save image to document directory in swift – Tutorial
Saving image to document directory of iOS app is very easy. As apple, already provided its own classes to store and retrieve image from document directory. We will use swift language, to save and retrieve image from document directory in iOS SDK.
Things we will cover
- Create a document directory
- Save image to document directory
- Delete image from document directory(if existed)
Creating a document directory in swift
We can use FileManager class to create a custom directory inside our document directory
func createDirectory(){ let fileManager = FileManager.default let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("customDirectory") if !fileManager.fileExists(atPath: paths){ try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil) }else{ print("Already directory existed with the name specified.") } }
Getting path for out custom directory in IOS using swift
//MARK: - getDirectoryPath func getDirectoryPathWithFileName(_ name:String) -> String { let paths = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("customDirectory") as NSString).appendingPathComponent(name) return paths }
Save image to document directory in swift iOS sdk
//MARK:- saveImageToDocumentDirectory func saveImageToDocumentDirectoryWith(_ imageName:String, andImageData imageData:Data) { let fileManger = FileManager.default let filePath = getDirectoryPathWithFileName(imageName) let isImageSaved = fileManger.createFile(atPath: filePath as String, contents: imageData, attributes: nil) print("IsIMageSaved == \(isImageSaved)") }
Delete image from document directory in swift
//MARK: - deleteFileWith func deleteFileWith(_ imageName:String) { let fileManger = FileManager.default let filePath = getDirectoryPathWithFileName(imageName) if fileManger.fileExists(atPath: filePath as String) { do { try fileManger.removeItem(atPath: filePath as String) } catch let error { print("Error Deleting file with name == \(imageName) with error == \(error.localizedDescription)") } } }