Save and Get Image from Document Directory in Swift

Every Apps have its own storage at Document directory. In Document directory user can store audio, video, image, pdf and others files. You can also read and write data of particular apps of Document directory. Document directory store the user data or file at path of apps. In this folder you can create other subfolders, files, and so on. You can read apps data from the path of document directory.
I wrote the code below for swift 4.0

How to Get Document Directory Path

func getDirectoryPath() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

How to Create Directory

func createDirectory(){
    let fileManager = FileManager.default
    let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("images")
    if !fileManager.fileExists(atPath: paths){
        do {
            try fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print("Couldn't create document directory")
        }
    }else{
        print("Already directory created.")
    }
}

How to Write / Save Image at Document Directory

func saveImageToDocumentDirectory() {
        let fileManager = FileManager.default
        let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("apple.jpg")
        let image = UIImage(named: "apple.jpg")
        let imageData = UIImageJPEGRepresentation(image!, 0.5)
        fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
    }

Read / Get Image from Document Directory

func getImage(imageName : String)-> UIImage{
        let fileManager = FileManager.default
// Here using getDirectoryPath method to get the Directory path
        let imagePath = (self.getDirectoryPath() as NSString).appendingPathComponent(imageName)
        if fileManager.fileExists(atPath: imagePath){
            return UIImage(contentsOfFile: imagePath)!
        }else{
            print("No Image available")
            return UIImage.init(named: "placeholder.png")! // Return placeholder image here
        }
    }

Delete Directory by Name

 func deleteDirectory(directoryName : String){
        let fileManager = FileManager.default
        let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(directoryName)
        if fileManager.fileExists(atPath: paths){
            try! fileManager.removeItem(atPath: paths)
        }else{
            print("Directory not found")
        }
    }
That’s it! We have successfully played with document directory.
If you like this post, Please comment below or subscribe this blog for latest update.
Leave your comments
Advertisements