Get image from documents directory swift

You are finding the document directory path at runtime for writing the image, for reading it back, you can use the exact logic:

Swift 3 and Swift 4.2

let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath          = paths.first
{
   let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png")
   let image    = UIImage(contentsOfFile: imageURL.path)
   // Do whatever you want with the image
}

Swift 2

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask
if let paths            = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
     if paths.count > 0
     {
         if let dirPath   = paths[0] as? String
         {
             let readPath = dirPath.stringByAppendingPathComponent("Image2.png")
             let image    = UIImage(contentsOfFile: readPath)
             // Do whatever you want with the image
         }
     }
}

Leave a Comment