rob rob - 26 days ago 23
Swift Question

No data coming in from parsing JSON with Alamofire Swift 3 and Xcode 8 beta

I am trying to get data from an url in Swift 3 with Alamofire. There is no data coming through on the cell. I know I am messing something up somewhere but I am fairly new to swift 3 and cant see the issue, the code is below:

JSON Structure.

{
posts: 
 [

 {
id: “000000”,
url: "/content/interview",
date: "2016-11-03 09:01:41",
modified: "2016-11-03 09:03:47",
title: "An interview",
summary: 
 {
value: "<p>Lorem ipsum is simply dummy text</p> ",
format: "filtered_html"
}
]
}


Swift:

import UIKit
import Alamofire


class TableViewController: UITableViewController {


var titles = [String]()

var mainURL = "https://www.testapi.com"

typealias JSONstandard = [String : AnyObject]

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
callAlamo(url: mainURL)
}

func callAlamo(url : String){
Alamofire.request(url).responseJSON(completionHandler: {
response in

self.parseData(JSONData: response.data!)


})

}

func parseData(JSONData : Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard

print(readableJSON)
if let post = readableJSON["posts"] as? JSONstandard {
if let posts = post["posts"] {
for i in 0..<posts.count {
let post = posts[i] as! JSONstandard

let title = post["title"] as! String
titles.append(title)

self.tableView.reloadData()

}
}

}

}


catch {
print(error)
}


}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

cell?.textLabel?.text = titles[indexPath.row]

return cell!
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}


The above bring no data into the "cell". Any help would be appreciated.

Answer

First of all a JSON dictionary in Swift 3 is [String:Any]

typealias JSONstandard = [String : Any]

The author of the tutorial should name it JSONdictionary to make it clearer.

The value for posts is an array, JSON collection objects are very easy to identify:

  • [] is array
  • {} is dictionary

  ...
  if let posts = readableJSON["posts"] as? [JSONstandard] {
     for post in posts { // don't use ugly C-style loops 
        let title = post["title"] as! String
        titles.append(title)
     }
     self.tableView.reloadData() // reload the table view after the loop
  }
  ...

PS : In Swift (1-3) passing .mutableContainers is pretty useless.

Comments