Swift - Write Image from URL to Local File
UIImagePNGRepresentaton() function had been deprecated. try image.pngData()
The following code would write a UIImage
in the Application Documents directory under the filename 'filename.jpg'
var image = .... // However you create/get a UIImage
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let destinationPath = documentsPath.stringByAppendingPathComponent("filename.jpg")
UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)
In Swift 3:
Write
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent("\(fileName).png")
if let pngImageData = UIImagePNGRepresentation(image) {
try pngImageData.write(to: fileURL, options: .atomic)
}
} catch { }
Read
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let filePath = documentsURL.appendingPathComponent("\(fileName).png").path
if FileManager.default.fileExists(atPath: filePath) {
return UIImage(contentsOfFile: filePath)
}
In swift 2.0, stringByAppendingPathComponent is unavailable, so the answer changes a bit. Here is what I've done to write a UIImage out to disk.
documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
if let image = UIImage(data: someNSDataRepresentingAnImage) {
let fileURL = documentsURL.URLByAppendingPathComponent(fileName+".png")
if let pngImageData = UIImagePNGRepresentation(image) {
pngImageData.writeToURL(fileURL, atomically: false)
}
}