Simple file upload with url

So I have the URL as a string (JPG in this case, but if a generic procedure for any type of file were possible) and I have the file path as a string where I want to save the file.

What would be the fastest way to accomplish this?

Please keep in mind that this is an OSX command line application. I tried several sample codes found here, mostly using UIImage, but I get the error: "Using unresolved identifier" adding "UIKit import" gets the error: "No such module". Please, help!

import Foundation

let myURLstring = "http://www.safety.vanderbilt.edu/images/staff/Bob-Wheaton.jpg"
let myFilePathString = "/Volumes/HD/Staff Pictures/Bob-VEHS.jpg"

      

---> ABOVE ORIGINAL QUESTION <---

---> BELOW NEW IMPROVED CODE: WORKING <---

import Foundation

let myURLstring = "http://www.safety.vanderbilt.edu/images/staff/Bob-Wheaton.jpg"
let myFilePathString = "/Volumes/HD/Staff Pictures/Bob-VEHS.jpg"

let url = NSURL(string: myURLstring)
let imageDataFromURL = NSData(contentsOfURL: url)

let fileManager = NSFileManager.defaultManager()
fileManager.createFileAtPath(myFilePathString, contents: imageDataFromURL, attributes: nil)

      

+3


source to share


2 answers


If you're writing for OS X, you use NSImage

instead UIImage

. To do this, you will need import Cocoa

- UIKit for iOS, Cocoa for Mac.

NSData

has an initializer that takes NSURL

and the other is a file path, so you can load the data anyway.



if let url = NSURL(string: myURLstring) {
    let imageDataFromURL = NSData(contentsOfURL: url)
}

let imageDataFromFile = NSData(contentsOfFile: myFilePathString)

      

+4


source


With Swift 4, the code would look like this:



if let url = URL(string: myURLstring) {
    let imageDataFromURL = try Data(contentsOf: url)
}

      

0


source







All Articles