Search code examples
iosswiftnsdocumentdirectory-ios8

Get image from documents directory swift


Say I were using this code to save an image to the documents directroy

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("Image.png")
        let image = UIImage(named: readPath)
        let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
        UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
    }
  }
}

How would I then retrive it? Keeping in mind than in iOS8 the exact path changes often


Solution

  • 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
             }
         }
    }