简体   繁体   中英

Swift3 - UIImageView isn't appearing from parsed JSON data

Hey guys would love some help with my first question. I've spent ages going through the forum but am still struggling to understand where I'm going wrong with this. The URL string is parsing fine from the JSON, however it is not displaying as an image in the UIImageView I have created. The code is compiling fine and everything else is displaying. I'm assuming I have to convert the URL which is type String to a UIImageView however I keep getting errors.

Here is the snippet of the EventCell class.

class EventCell: UICollectionViewCell {

var event: Event?   {
    didSet  {

        if let eventName = event?.title {
            eventTitle.text = eventName
        }

        eventSubtitle.text = event?.subtitle

        eventTags.text = event?.tags

        if let imageName = event?.imageURL
        {
            imageView.image = UIImage(named: imageName)
        }
    }
}

override init(frame: CGRect)    {
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}


let imageView: UIImageView =  {
    let iv = UIImageView()
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.contentMode = .scaleAspectFill
    return iv
}()

And here is the snippet of the Event class itself.

var id: NSNumber?
var title: String?
var imageURL: String?
var subtitle: String?
var tags: String?
var desc: String?

override init(){}

init(event: NSDictionary)
{
    if let val = event["ID"] as? NSNumber
    {
        id = val;
    }

    if let val = event["Title"] as? String
    {
        title = val;
    }

    if let val = event["Subtitle"] as? String
    {
        subtitle = val;
    }

    if let val = event["Tags"] as? String
    {
        tags = val;
    }

    if let val = event["Description"] as? String
    {
        desc = val;
    }

    if let val = event["image"] as? String
    {
        imageURL = val;
    }
}

Any help would be much appreciated! Thanks!

The initialiser UIImage(named:) expects the name of an image that is already stored in the bundle. In your case, you want to load an image from a URL . What you should do is create a URL from the String , then load the contents of that URL as NSData and finally create a UIImage from that Data . The quickest way to achieve this is

if let imageURLString = event?.imageURL {
    let imageURL = URL(string: imageURLString!)
    let imageData = NSData(contentsOf: imageURL!)
    imageView.image = UIImage(data: imageData as! Data)
}

NOTE

A few points to take into consideration

  • This is not the best approach to load an image from a URL . You should also look into async requests. However, this is the quickest implementation and should get the code working
  • The snippet is in Swift 3 syntax. I'm assuming you can convert it to Swift 2 if that's what you are using

As per Apple documentation UIImage(named:) expects name of the name in your app bundle. You can pass the url of your image in dataWithContentsOfURL: method. Though using this approach is fine, you just need to process asynchronously as approach with dataWithContentsOfURL: is a synchronous request and blocks the main thread until that download is complete.

Consider using SDWebImage an UIImageView extension, it adds to manage the image download and display. It also supports a placeholder image that you can supply to indicate that the download is in progress.

Hope it helps. Happy Coding!!

add this extension

extension UIImageView {
    public func imageFromUrl(urlString: String) {
        if let url = URL(string: urlString) {
            URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
                if (error != nil) {
                    print(error?.localizedDescription ?? "no errror")
                }
                else {
                    if let image = UIImage(data: data!) {
                        DispatchQueue.main.async {
                            self.image = image
                        }
                    }
                }
            }).resume()
        }
    }
}

usage :

imageView.imageFromUrl(urlString: "http://linktoyourimage.com")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM