rob rob - 29 days ago 27
iOS Question

JSON structure with Swift and Alamofire

Following on from This question

I am trying to bring in the summary field but it has a further value. I have brought in the title and author as follows:

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

if let posts = readableJSON["posts"] as? [JSONstandard] {
for post in posts {
let title = post["title"] as! String

let author = post["author"] as! String

let summary = post["summary"] as! String

print(author)

if let imageUrl = post["image"] as? String {
let mainImageURL = URL(string: imageUrl )
let mainImageData = NSData(contentsOf: mainImageURL!)
let mainImage = UIImage(data: mainImageData as! Data)

postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}

}

catch {
print(error)
}
}


But if i try the summary that way a error is returned. Any help would be appreciated.

JSON STRUCTURE

{
"posts" : [{
"id": "000000",
"url": "/content/interview2",
"date": "2016-11-03 09:01:41",
"modified": "2016-11-03 09:03:47",
"title": "An interview",
"image": "https://www.example.com/sites/default/files/oregood.jpeg",
"summary": {
"value": "<p>Latin text here</p>",
"format": "filtered_html"
}
}]
}

Answer

From your previous question response, summary key contains the Dictionary so you can try like this.

guard let dic = post["summary"] as? [String: Any], let summary = dic["value"] as? String else {
    return
}