Skip to content

Instantly share code, notes, and snippets.

@hiddevdploeg
Last active July 11, 2016 19:12
Show Gist options
  • Save hiddevdploeg/9b441e12dbb04ab090a2 to your computer and use it in GitHub Desktop.
Save hiddevdploeg/9b441e12dbb04ab090a2 to your computer and use it in GitHub Desktop.
Easy function to return a single image from an URL
func imageURL(URL: String) -> UIImage {
guard let base = NSURL(string: URL),
let data = NSData(contentsOfURL: base),
let image = UIImage(data:data) else {
return nil
}
return image
}
//USAGE EXAMPLE: imagevar.image = imageURL("http://logonoid.com/images/star-wars-logo.png")
@NatashaTheRobot
Copy link

Force unwrapping optionals is a bad idea! The URL might be invalid, so you have to return an optional UIImage or decide to throw an error. Consider something like this instead:

func imageFromURL(URL: String) -> UIImage? {
    guard let base = NSURL(string: URL),
        let data = NSData(contentsOfURL: base),
        let image = UIImage(data:data) else {
            return nil
     }

     return image
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment