Monday, 26 October 2015

Save image to document directory in swift - Tutorial



Save image to document directory in swift - Tutorial











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 director and you will get images saved there. If you run this code again you will see that compiler will enter 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

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

No comments:
Write comments