0

I am trying to download a list of articles and insert it into a table view. However I seem to be having an issue retrieving the JSON file and parsing it.

My code is as follows:

    override func viewDidLoad() {
        super.viewDidLoad()

        self.downloadArticles()

        self.tableView.reloadData()
    }


   func downloadArticles(){
        var url: NSURL
        url = NSURL(string: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url=%27www.abc.net.au%2Fnews%2Ffeed%2F51120%2Frss.xml%27&format=json")!
        print(url)
        let task = NSURLSession.sharedSession().dataTaskWithURL(url){
            (data, response, error) in
            if (error != nil){
                print("Error \(error)")
            } else{
                self.parseArticleJSON(data!)
            }
            self.syncCompleted = true
            self.tableView.reloadData()
        }
        task.resume()
    }

    func parseArticleJSON(articleJSON:NSData)
    {
        do{

            let result = try NSJSONSerialization.JSONObjectWithData(articleJSON, options: NSJSONReadingOptions.MutableContainers) as? NSArray

            //let jsonData:NSArray = (try NSJSONSerialization.JSONObjectWithData(articleJSON, options:NSJSONReadingOptions.MutableContainers) as? NSArray)!

            let newArticlesArray = result as NSArray!
            //NSLog("Found \(newArticlesArray.count) new articles!")
            for article in (newArticlesArray as NSArray as! [NSDictionary])
            {
                print (article.objectForKey("title")! as? String)

                //let a = Article (t: <#T##String#>, da: <#T##String#>, de: <#T##String#>, i: <#T##NSURL#>)

                //articlesArray.addObject(a);
            }
        }catch {
            print("JSON Serialization error")
        }

    }

In the parseArticleJSON method (I know it is not all completely finished). I get the error at line:

for article in (newArticlesArray as NSArray as! [NSDictionary])

it says:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have tried doing some research here on these forums, but I was unable to find any response that would be of help to me so I was wondering if somebody would be able to help me.

I need to use the native swift JSON methods to do all this.

Thanks in advance!

1
  • Hi, as your result variable could be null and IS optional, the for...in instruction should use variables with optional wrappers too i.e 'as?'. Give it a try... Commented Apr 16, 2016 at 6:56

2 Answers 2

2

The JSON is much more nested:

typealias JSONDictionary = Dictionary<String,AnyObject>

func parseArticleJSON(articleJSON:NSData) {
  do {
    let jsonObject = try NSJSONSerialization.JSONObjectWithData(articleJSON, options: [])
    if let jsonResult = jsonObject as? JSONDictionary,
      query = jsonResult["query"]  as? JSONDictionary,
      results = query["results"]  as? JSONDictionary,
      newArticlesArray = results["item"]  as? [JSONDictionary] {
      for article in newArticlesArray {
        print(article["title"] as! String)
      }
    }
  } catch let error as NSError {
    print(error)
  }
}

For that deeply nested JSON it's recommended to use a library like SwiftyJSON.

Since the code is only reading the JSON object, the option MutableContainers is not needed at all and in Swift always use native collection types unless you have absolutely no choice.

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

Comments

0

try this code,

if let jsonObject: AnyObject = NSJSONSerialization.JSONObjectWithData(articleJSON, options: nil, error:&error) {
    if let dict = jsonObject as? NSDictionary {
        println(dict)
    } else {
        println("not a dictionary")
    }
} else {
    println("Could not parse JSON: \(error!)")
}

hope its helpful

Comments

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.