我有一个扩展程序允许我UITableView
从 API 下载图像到我的。
extension UIImageView {
func donwloadImage(from url: String) {
let urlRequest = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error)
return
}
DispatchQueue.main.async {
self.image = UIImage(data: data!)
}
}
task.resume()
}
}
imageUrl
如果是,则应用程序崩溃nil
。
如果没有图像,我该如何包装它,??
所以它只是空白?UIImageView
这是一个数据模型和获取数据功能
class Article: NSObject {
var headline: String?
var date: String?
var imageUrl: String?
var desc: String?
var url: String?
}
@objc func fetchArticles() {
let urlRequest = URLRequest(url: URL(string: "https://newsapi.org/v2/everything?pageSize=15&sortBy=publishedAt&apiKey=API_KEY")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error)
return
}
self.articles = [Article]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let articlesFromJson = json["articles"] as? [[String: AnyObject]] {
for articlesFromJson in articlesFromJson {
let article = Article()
if
let title = articlesFromJson["title"] as? String,
let publishedAt = articlesFromJson["publishedAt"] as? String,
let urlToImage = articlesFromJson["urlToImage"] as? String,
let description = articlesFromJson["description"] as? String,
let url = articlesFromJson["url"] as? String
{
article.headline = title
article.date = publishedAt
article.imageUrl = urlToImage
article.desc = description
article.url = url
}
self.articles?.append(article) // and so on...