Coder123
Coder123

Reputation: 854

Saving image from gallery to iOS app

I am new to Swift and I am trying to save an image from the gallery of the phone (or the Internet) to my app. I found many tutorials showing how to view the image but not how to save it to my app (I guess to my assets folder) and use it later on. Can someone please pint me to the right direction?

Upvotes: 1

Views: 1058

Answers (1)

Firat Eski
Firat Eski

Reputation: 671

func saveImage (image: UIImage, path: String ) -> Bool{

    let pngImageData = UIImagePNGRepresentation(image)
    //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
    let result = pngImageData!.writeToFile(path, atomically: true)

    return result

}

Here is how to use the function later in your code:

saveImage(image, path: imagePath)

However before you can Save or Load anything you have to know the ‘path’ you are going to use. We’ll need 3 things:

  • a function to pinpoint the documents directory
  • a file in the documents directory a function to pinpoint
  • a variable to store the location ( path ) of the image we want to save

Here is how we are going to do that:

    func getDocumentsURL() -> NSURL {
    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    return documentsURL
}

func fileInDocumentsDirectory(filename: String) -> String {

    let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
    return fileURL.path!

}

// Define the specific path, image name
let imagePath = fileInDocumentsDirectory(myImageName)

Visit for more: http://helpmecodeswift.com/image-manipulation/saving-loading-images

Upvotes: 3

Related Questions