Swift - Write Image from URL to Local File Swift - Write Image from URL to Local File json json

Swift - Write Image from URL to Local File


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").pathif FileManager.default.fileExists(atPath: filePath) {    return UIImage(contentsOfFile: filePath)}


The following code would write a UIImage in the Application Documents directory under the filename 'filename.jpg'

var image = ....  // However you create/get a UIImagelet documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as Stringlet destinationPath = documentsPath.stringByAppendingPathComponent("filename.jpg")UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)


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