43

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

Learnin
  • 1,221
  • 4
  • 15
  • 19

5 Answers5

120

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
         }
     }
}
zeeshan
  • 4,913
  • 1
  • 49
  • 58
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • Thanks! Also, how would i use filemanager.fileExistsAtPath to check whether there is a file at that read path? – Learnin Mar 13 '15 at 00:27
  • 1
    @Learnin: You can check like : `var fileMngr = NSFileManager.defaultManager() if (fileMngr.fileExistsAtPath(readPath)){ // File Exist }` – Midhun MP Mar 13 '15 at 05:48
14

Better as an extension.

extension URL {
    static var documentsDirectory: URL {
        let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        return try! documentsDirectory.asURL()
    }

    static func urlInDocumentsDirectory(with filename: String) -> URL {
        return documentsDirectory.appendingPathComponent(filename)
    }
}

Used like this:

let path = URL.urlInDocumentsDirectory(with: filename).path
let image = UIImage(contentsOfFile: path)
Reid
  • 734
  • 8
  • 15
10

Load multiple images from the folder or directory. - Swift 4

Here's the image attached to show, what we want to achieve in the given below code. enter image description here

Here's the code to find the multiple images from the folder in documents directory. I have written one method to do the same.

In the code we are passing the "Folder Name" (ie. Red) and getting the contents of that directory. In return we got the array of images name.

    static func loadImagesFromAlbum(folderName:String) -> [String]{

    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
    let paths               = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    var theItems = [String]()
    if let dirPath          = paths.first
    {
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(folderName)

        do {
            theItems = try FileManager.default.contentsOfDirectory(atPath: imageURL.path)
            return theItems
        } catch let error as NSError {
            print(error.localizedDescription)
            return theItems
        }
    }
    return theItems
}

Here's the result of given code. enter image description here

Hope it helps.

Thanks

Harjot Singh
  • 6,767
  • 2
  • 38
  • 34
9

Swift 2

If you want to get a file from your document directory in Swift 2:

let path: String? = NSBundle.mainBundle().pathForResource("imageName", ofType: "png", inDirectory: "DirectoryName/Images")
let imageFromPath = UIImage(contentsOfFile: path!)!
self.myImage.image = imageFromPath

Hope that helps somebody

smoosh911
  • 516
  • 7
  • 8
-1
// --------------------------------------------------------
// MARK:- Document Directory
// --------------------------------------------------------

///# Get Data from document directory #///

private func getDocumentData(){
    
    ///# Path #///
    
    let folderPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("MyZipFiles") /// * folder *///
    let filePath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)") ///* inside folder all files *///
    print(filePath)

    ///# Get JsonFile from Directory with alamofire #///
    
    let jsonFilePath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/python.json") ///* inside filename *///
    if (try! jsonFilePath.checkResourceIsReachable()) {
        print("file exist")
        Alamofire.request(jsonFilePath, method: .get, parameters: nil).responseData { (response) in
            guard let data = response.data else { return }
            do{
                let json = try SwiftyJSON.JSON(data: data)
                let results = json["images"]
                for arr in results.arrayValue{
                    self.arrImageData.append(Images(json: arr))
                }
                self._pickerCollectionView.reloadData()
                print(self.arrImageData)
            }catch{
                print(error.localizedDescription)
            }
        }

        ///# Back  Video #///
        let backVideoPath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/background_video.mp4") ///* inside filename *///
        print(backVideoPath)

        
        ///# Output Video #///
        let outputPath = URL(fileURLWithPath: folderPath).appendingPathComponent("\(self.id)/\(self.titleVideo)/output.mp4")
        print(outputPath)

        ///# Get images string from documentdirectory #///
        
        do {
            let imagesData = try FileManager.default.contentsOfDirectory(atPath: filePath.path)  ///* Base Path to find Image *///
            
            ///# for loop to append path to find saved images and fill image array #///
            
        for imgStr in imagesData{
            if imgStr.hasPrefix("img"){
                imagesArr.append(imgStr)
                print(imagesArr)
                let document = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("MyZipFiles")
                print(document)
                
                let loadImage = document.appendingPathComponent("\(self.id)/\(self.titleVideo)")
                
                let imgUrl = loadImage.appendingPathComponent(imgStr, isDirectory: true)
                print(imgUrl.path)

                if let data = UIImage(named: imgStr)?.pngData() ,
                   !FileManager.default.fileExists(atPath: imgUrl.path){
                    do{
                        ///* write data to convert string images into url in document folder *///
                        
                        try data.write(to: imgUrl)
                        print("Image Add Successfully")
                        Log.debug(imgStr)
                    }
                    catch{
                        print("Image Not Added")
                    }
                }
                ///* append written url into array of images *///

                imgArr.append(imgUrl)
            }
        }
    }
        catch let err{
            print(err.localizedDescription)
        }
    }
}