0

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()
    }
9
  • Are you getting nil for urlToImage from server? Commented Dec 18, 2017 at 8:06
  • Yes, I get the returned JSON and sometimes one of the articles has a nil from the server. right now I have a default image in place, but I would like to skip the item entirely. Commented Dec 18, 2017 at 8:10
  • Then don't append that object into your articles array if urlToImage is nil Commented Dec 18, 2017 at 8:11
  • Novice question I know, but could you give me an example? Commented Dec 18, 2017 at 8:13
  • As I am seeing from your code 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 { is correct according to me. Commented Dec 18, 2017 at 8:15

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Would I insert the filter after reloading the data? Or right after appending the article?
After the for loop you use to append the items.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.