Reputation: 854
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
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:
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