I've a JSON (for now in local), that I want to parse to put these data in a listView.
I've already created the view and tried a few things (like this tutorial : https://www.journaldev.com/21839/ios-swift-json-parsing-tutorial) to parse that JSON, with no success.
Here is some code I tried :
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var labelHeader: UILabel!
@IBOutlet weak var tableView: UITableView!
var channelList = [channelData]()
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "channels", withExtension: "json")
guard let jsonData = url
else{
print("data not found")
return
}
guard let data = try? Data(contentsOf: jsonData) else { return }
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else{return}
if let dictionary = json as? [String: Any] {
if let title = dictionary["title"] as? String {
print("in title")
labelHeader.text = title
}
if let data = dictionary["data"] as? Any {
print("data is \(data)")
}
if let date = dictionary["date"] as? Date {
print("date is \(date)")
}
// And so on
for (key, value) in dictionary {
print("Key is: \(key) and value is \(value)" )
//This print the whole JSON to the console.
}
}
//Now lets populate our TableView
let newUrl = Bundle.main.url(forResource: "channels", withExtension: "json")
guard let j = newUrl
else{
print("data not found")
return
}
guard let d = try? Data(contentsOf: j)
else { print("failed")
return
}
guard let rootJSON = try? JSONSerialization.jsonObject(with: d, options: [])
else{ print("failedh")
return
}
if let JSON = rootJSON as? [String: Any] {
labelHeader.text = JSON["id"] as? String //Should update the Label in the ListView with the ID found in the JSON
guard let jsonArray = JSON["type"] as? [[String: Any]] else {
return
}
let name = jsonArray[0]["name"] as? String
print(name ?? "NA")
print(jsonArray.last!["date"] as? Int ?? 1970)
channelList = jsonArray.compactMap{return channelData($0)}
self.tableView.reloadData()
}
}
Here is a sample of the JSON file :
{
"format": "json",
"data": [
{
"type": "channel",
"id": "123",
"updated_at": "2019-05-03 11:32:57",
"context": "search",
"relationships": {
"recipients": [
{
"type": "user",
"id": 321,
"participant_id": 456
}
],
"search": {
"type": "search",
"title": "Title"
},
}
},
I'd like to find the best way to work with kind of this JSON.
For now I'm not able to get the data to the listView. The most I have is my JSON in the console of xCode (at least it means I'm able to open the JSON).