-1

When I try to load an image from a URL I always get an error despite the fact that I know that there is a URL that contains a valid .jpg image.

mainImageView.image = try UIImage(data: Data(contentsOf: URL(fileURLWithPath: artworkURL)))

I also tried these solution but the line where I initialise the UIImage still throws an error.

Example of data in artworkURL:

http://is1.mzstatic.com/image/thumb/Music/v4/ef/97/95/ef979538-8321-151a-dceb-9b0a7f7c7641/source/100x100bb.jpg

Current solutions do not solve my problem. I also tried:

try UIImage(data: Data(contentsOf: URL(string: artworkURL)!))

and

try UIImage(data: Data(contentsOf: (URL : artworkURL)))

and (fuller code) now using a static url to debug

let artworkString = "http://is1.mzstatic.com/image/thumb/Music/v4/ef/97/95/ef979538-8321-151a-dceb-9b0a7f7c7641/source/100x100bb.jpg" // album.artworkURL[index.row]
let url = URL(string: artworkString)

do {
    mainImageView.image = try UIImage(data: Data(contentsOf: url!))
} catch _ {
    print("No album artwork!")
}

This last one outputs "No album artwork!"!

Community
  • 1
  • 1
Max Goodridge
  • 373
  • 2
  • 7
  • 21
  • @EricAya I *am* using try!!! – Max Goodridge Sep 20 '16 at 11:00
  • @MaxGoodridge Then it should work. Look at [my screenshot](https://www.evernote.com/l/AOwJ4q4PUmlArK-NlffFMDt-DwjjnWho8Fs), using your exact same code. Your issue is elsewhere, not here. – Eric Aya Sep 20 '16 at 11:01
  • I can't answer my own question for some reason but [this](http://stackoverflow.com/a/31807139/4548304) is the answer!! I had to add a breakpoint (for the first time) to find the error. – Max Goodridge Sep 20 '16 at 11:25
  • 1
    @EricAya Duely noted - I learned a lot about how to actually debug code using Xcode trying to find the solution. Please forgive me for my lack of competence debugging in Xcode. – Max Goodridge Sep 20 '16 at 12:07

1 Answers1

0

You can user this library:

https://github.com/onevcat/Kingfisher

Kingfisher is a lightweight, pure-Swift library for downloading and caching images from the web. This project is heavily inspired by the popular SDWebImage. It provides you a chance to use a pure-Swift alternative in your next app.

let imagePath = URL(string: "url_of_your_image")    
imageView.kf_setImageWithURL(NSURL(string: imagePath)!, placeholderImage: UIImage(named: "placeholder"))

you can also add placeholder image.

Amit Kumar Sahu
  • 495
  • 6
  • 15