Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Write Image from URL to Local File

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) {     println(results)     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!

Thanks,

tvick47

like image 814
Tyler Avatar asked Oct 03 '14 01:10

Tyler


People also ask

How to download image from link Swift?

Open ViewController. swift and create an outlet with name imageView of type UIImageView! , an implicitly unwrapped optional. The idea is simple. The view controller downloads an image from a URL and displays it in its image view.

How do I save an image in a directory in Swift?

To write the image data to the Documents directory, we invoke the write(to:) method on the Data object. Because the write(to:) method is throwing, we wrap the method call in a do-catch statement and prefix it with the try keyword.

What is UIImage?

An object that manages image data in your app.

How do I save an image in Userdefaults swift 5?

We ask the FileManager class for the URL of the Documents directory and append the name of the file, landscape. png, to the URL. Writing a Data object to disk is a throwing operation so we wrap it in a do-catch statement. If the operation is successful, we store the URL in the user's defaults database.


2 Answers

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) } 
like image 76
JPetric Avatar answered Sep 18 '22 07:09

JPetric


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) 
like image 33
kurtn718 Avatar answered Sep 19 '22 07:09

kurtn718