4

我有一个扩展程序允许我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...
4

1 回答 1

0

我建议你使用一个异步下载图像的 POD,并且总是留下一个 placeHolder 的图像,看下面使用它的例子:

import SDWebImage

imageView.sd_setImage (
   with: URL (string: "http://www.example.com/image.jpg"), 
   placeholderImage: UIImage (named: "placeholder.png") // define your default Image
)

POD 链接:https ://cocoapods.org/pods/SDWebImage

希望这可以帮助。

于 2020-02-02T20:28:49.110 回答