5

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

What would be the fastest way to get this implemented?

Please keep in mind this is for OSX command line application. I tried few sample codes found here, mostly using UIImage but I get error:"Use of unresolved identifier", adding "import UIKit" gets me 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 IS THE ORIGINAL QUESTION <---

---> BELOW IS 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)
54 69 6D
  • 674
  • 8
  • 17
Gio
  • 65
  • 1
  • 1
  • 7

2 Answers2

5

If you're writing for OS X, you'll use NSImage instead of UIImage. You'll need import Cocoa for that - UIKit is for iOS, Cocoa is for the Mac.

NSData has an initializer that takes a NSURL, and another that takes a file path, so you can load the data either way.

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

let imageDataFromFile = NSData(contentsOfFile: myFilePathString)
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • Thxs! And Thxs for the Cocoa tip!! Your code gave me an error in the "if" statement: "Bound value in conditional binding most be of an Optional type". Removing the conditional and leaving the "url" declaration by itself takes away the error but not sure of it's relevance :) can you please explain? UPDATE: I got it working now THX!!!!! Still not sure of the “if” but is working without it. I’ll update the code in the original post for everyone's reference. – Gio Oct 16 '14 at 20:46
  • That's likely an Xcode 6.0 - 6.1 difference - they added failable initializers somewhere along the way. When you update you'll need to switch back to this version. :) – Nate Cook Oct 16 '14 at 21:18
3

With Swift 4, the code will be:

if let url = URL(string: myURLstring) {
    let imageDataFromURL = try Data(contentsOf: url)
}
OlivierM
  • 2,820
  • 24
  • 41