I am learning Swift, and I am encountering an issue parsing a JSON file from a URL file.
I'm trying to call the posts
dictionary and parse the audio
values from it.
let url = URL(string: "https://api.myjson.com/bins/91nzd")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let posts = json["posts"] as? [String: Any] ?? [:]
print(posts)
let audios = posts["audio"] as? [String: Any] ?? [:]
print(audios)
} catch let error as NSError {
print(error)
}
}).resume()
This returns :, :
which I believe is a nil expression. The JSON file it is calling looks like this:
{
"posts": [
{
"id": "1",
"title": "title 1",
"audio": "https://rss-example.com/episodes/871ae23d.mp3"
},
{
"id": "2",
"title": "title 2",
"audio": "https://rss-example.com/episodes/352ae29d.mp3"
}
]
}
This looks right to me from the tutorials I have read, but do you see an error? Or am I misinterpreting?