Ben Shaw
Ben Shaw

Reputation: 77

Filter/ flatMap out objects with any nil values from array in swift 4

I am filling in a UICollectionView with results from a query. Sometimes, the resulting stories don't have images. I would like to skip those objects entirely.

How can I skip over results from a JSON query that don't have any image present? It looks like I should use flatMap, but can't get it going.

Here is the code I'm using:

 @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()
    }

Upvotes: 0

Views: 328

Answers (1)

t4nhpt
t4nhpt

Reputation: 5302

There are two ways to solve this:

  • Don't append the article if the urlToImage nil

  • Append everything, but then filter the items with image only:

    let hasImageArticles = articles.filter({ $0.imageURL != nil })

Upvotes: 1

Related Questions