Swift - Write Image from URL to Local File

swift load image from path
save image to file manager swift
swift save image to photo library
save image to local ios swift
swift 4 save image to file
save uiimage to url swift
how to save image in userdefaults swift 4
convert uiimage to url swift 4

I've been learning swift rather quickly, and I'm trying to develop an OS X application that downloads images.

I've been able to parse the JSON I'm looking for into an array of URLs as follows:

func didReceiveAPIResults(results: NSArray) {
    for link in results {
        let stringLink = link as String
        //Check to make sure that the string is actually pointing to a file
        if stringLink.lowercaseString.rangeOfString(".jpg") != nil {2

            //Convert string to url
            var imgURL: NSURL = NSURL(string: stringLink)!

            //Download an NSData representation of the image from URL
            var request: NSURLRequest = NSURLRequest(URL: imgURL)

            var urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)!
            //Make request to download URL
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
                if !(error? != nil) {
                    //set image to requested resource
                    var image = NSImage(data: data)

                } else {
                    //If request fails...
                    println("error: \(error.localizedDescription)")

So at this point I have my images defined as "image", but what I'm failing to grasp here is how to save these files to my local directory.

Any help on this matter would be greatly appreciated!



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)

How to save a UIImage to a file using jpegData , If you've generated an image using Core Graphics, or perhaps both of which convert a UIImage into a Data instance you can write out. func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: . Let’s see this with help of an example. Create an empty project and add an empty Image view. Create its outlet and then we’ll write the code to get image from an URL. This is how our application looks at the moment. Now, let’s add code to get image from an URL.

In Swift 3:


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


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)

Save Images Locally with Swift 5, We will be using UserDefaults and file system in order to save locally. To get Basically all this method will do is get the url for the home directory on the device. You should now be able to write the image data to disk. In some reasons, you might want to store an UIImage, that is generated using Core Graphics, or from device’s Photo Gallery via UIImagePickerController, to a local file as PNG or a JPEG format. By using UIImagePNGRepresentation () or UIImageJPEGRepresentation (), UIImage will be converted into Data so you can write it to local file easily.

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)

Swift 3, Here's a trivial example of writing an image to disk as a PNG and then reading it back. func addSkipBackupAttributeToItem(atPath path: String) -> Bool { var url fileExists(atPath: path), "File \(path) does not exist") var success: Bool do { var� If you've generated an image using Core Graphics, or perhaps rendered part of your layout, you might want to save that out as either a PNG or a JPEG. Both are easy thanks to two methods: pngData() and jpegData() , both of which convert a UIImage into a Data instance you can write out.

UIImagePNGRepresentaton() function had been deprecated. try image.pngData()

Persisting Image Data Locally (swift 3) | by Doug Galante, In this post I'll go over how to persist image data locally on your phone. Lets set up an entity that will be used to store the file path and write a method a unique name for our photo, and get the URL to save the photo data. You could supply the directory the files were in as the baseURL, and then just create the URLs with the file name as the Swift String path. Converting URL back to a Swift String. Sometimes, especially when dealing with older API, or when showing it to the user, you need to convert a URL object back to a Swift String. Thankfully, URL provides a

@IBAction func savePhoto(_ sender: Any) {

        let imageData = UIImagePNGRepresentation(myImg.image!)
        let compresedImage = UIImage(data: imageData!)
        UIImageWriteToSavedPhotosAlbum(compresedImage!, nil, nil, nil)

        let alert = UIAlertController(title: "Saved", message: "Your image has been saved", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default)
        self.present(alert, animated: true)

[Swift] How to store UIImage to a local file?, UIImage will be converted into Data so you can write it to local file easily. public static func storeImageToDocumentDirectory(image: UIImage, fileName: function getting the file URL of the location you want to store a file. UIImageView is designed to load only local images, but with a little work you can make it load remote images too. To get a basic solution, add an extension to UIImageView that downloads image data using a GCD background thread, then converts that to a UIImage, and loads it back into the image view on the main thread:

Download Files on iOS, Create local filesystem URL let localURL = URL(string: "path/to/image")! // Download to the local filesystem let downloadTask = islandRef.write(toFile: localURL)� Storing images. The idea here is to be able to take an image that has been loaded into the current web page and store it into localStorage. As we established above, localStorage only supports strings, so what we need to do here is turn the image into a Data URL. One way to do this for an image, is to load into a canvas element.

Save And Get Image From Document Directory, In This Blog, We Learn How to Save And Get Image From Document Directory. When We Not Work With Any Enter Swift as Language and choose Next. Now Open View Controller Class File And Create Outlet Of Image View. This Function Return Directory Path As Url. 0 Comment Write a Comment� For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide. URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference.

Take, save and retrieve a photo — iOS #13, As in, using the photo library like a local database? Open the ViewController. swift file and we'll add code to take photos! the second line stores in our imageView variable the image that was taken by the camera. There's way more things we can do to images — write on them, apply filters etc and also� ImageSource load images from local files or the Web.There are many different types of using images in Xamarin Forms. FromFile - Requires a filename or filepath that can be resolved on each

  • Thanks for the response! However, whenever I try to build with that code I receive the error: Use of unresolved identifier 'UIImageJPEGRepresentation'
  • That function exists on iOS. Here's how to do it using Mac APIs in Objective-C. Will post Swift version stackoverflow.com/questions/3038820/…
  • Thanks for the update! Although I do understand a bit further, a swift version would really help me out. Thanks!
  • String doesn't have stringByAppendingPathComponent
  • great answer - please consider to add info about image deletion
  • I am trying to use UIImagePNGRepresentation() function but Xcode does not recognize it for some reason. I am using Swift 4.2.
  • try pngData() PNG is changed