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
Swift
x
9
1
func createDirectory(){
2
let fileManager = FileManager.default
3
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("customDirectory")
4
if !fileManager.fileExists(atPath: paths){
5
try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
6
}else{
7
print("Already directory existed with the name specified.")
8
}
9
}
Getting path for out custom directory in IOS using swift
Swift
xxxxxxxxxx
1
5
1
//MARK: - getDirectoryPath
2
func getDirectoryPathWithFileName(_ name:String) -> String {
3
let paths = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("customDirectory") as NSString).appendingPathComponent(name)
4
return paths
5
}
Save image to document directory in swift iOS sdk
Swift
xxxxxxxxxx
1
7
1
//MARK:- saveImageToDocumentDirectory
2
func saveImageToDocumentDirectoryWith(_ imageName:String, andImageData imageData:Data) {
3
let fileManger = FileManager.default
4
let filePath = getDirectoryPathWithFileName(imageName)
5
let isImageSaved = fileManger.createFile(atPath: filePath as String, contents: imageData, attributes: nil)
6
print("IsIMageSaved == \(isImageSaved)")
7
}
Delete image from document directory in swift
Swift
xxxxxxxxxx
1
12
12
1
//MARK: - deleteFileWith
2
func deleteFileWith(_ imageName:String) {
3
let fileManger = FileManager.default
4
let filePath = getDirectoryPathWithFileName(imageName)
5
if fileManger.fileExists(atPath: filePath as String) {
6
do {
7
try fileManger.removeItem(atPath: filePath as String)
8
} catch let error {
9
print("Error Deleting file with name == \(imageName) with error == \(error.localizedDescription)")
10
}
11
}
12
}