我正在使用查询结果填充UICollectionView。有时候,由此产生的故事没有图像。我想完全跳过这些对象。
如何跳过没有任何图像的JSON查询的结果?看起来我应该使用flatMap,但无法实现。
这是我正在使用的代码:
@objc func fetchArticles(fromSource provider: String) {
let urlRequest = URLRequest(url: URL(string:"https://newsapi.org/v2/top-headlines?category=\(provider)&language=en&apiKey=apikeyremoved")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
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 articleFromJson in articlesFromJson {
let article = Article()
if let title = articleFromJson["title"] as? String, let author = articleFromJson["author"] as? String, let desc = articleFromJson["description"] as? String,let url = articleFromJson["url"] as? String, let urlToImage = articleFromJson["urlToImage"] as? String {
article.author = author
article.desc = desc
article.headline = title
article.url = url
article.imageURL = urlToImage
}
self.articles?.append(article)
}
}
DispatchQueue.main.async {
self.collectionview.reloadData()
}
}catch let error {
print(error)
}
}
task.resume()
}
有两种方法可以解决这个问题:
urlToImage
为零,请不要附加文章