In iOS, if you need to save image to local disk of iPhone then you need to save it document directory of the app.This post contains tutorial for saving image to document directory using Swift3. Below is the code for saving Image to document directory in swift3 language.
Get path of document directory
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let getImagePath = paths.appending(“index.jpg”)
let checkValidation = FileManager.default
Check if there is already an image with same name then delete it
if (checkValidation.fileExists(atPath: getImagePath)) {
//remove file as its already existed
}
else {
//write file as its not available
}
Write new image to document directory
if (checkValidation.fileExists(atPath: getImagePath))
{
//remove file as its already existed
try! checkValidation.removeItem(atPath: getImagePath)
}
else
{
//write file as its not available
let imageData = UIImageJPEGRepresentation(UIImage(named: “iTunesArtwork.png”)!, 1.0)
try! imageData?.write(to: URL.init(fileURLWithPath: getImagePath), options: .atomicWrite)
}
Check your document directory and you will get images saved there. If you run this code again you will see that compiler will enter in the remove file block.
Where to go from here:
In this post you learned how to save image to document directory in swift3. Check out the complete code here that shows how to save image to document directory in swift
Complete code:
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let getImagePath = paths.appending(“index.jpg”)
let checkValidation = FileManager.default
if (checkValidation.fileExists(atPath: getImagePath))
{
//remove file as its already existed
try! checkValidation.removeItem(atPath: getImagePath)
}
else
{
//write file as its not available
let imageData = UIImageJPEGRepresentation(UIImage(named: “iTunesArtwork.png”)!, 1.0)
try! imageData?.write(to: URL.init(fileURLWithPath: getImagePath), options: .atomicWrite)
}
Like this:
Like Loading...