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!
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")