Not able to parse the JSON data from F1 url - json

I am trying to access JSON data using the following url http://ergast.com/api/f1/1950/driverstandings.json
Now I am able to access the data with the following function.
In other words I am able to show the data in the console. The issue I am having is parsing the JSON data.
I am using Swifty JSON to parse the data and for some reason I am not able to show the data from the API.
The function below updates the UILabel on the storyboard.
Any help would be appreciated. Below is the entire code for the problem that I am what to solve. I want to add that there is year for the url is coming a UIPickerView on another view.
import UIKit
import Alamofire
import SwiftyJSON
class StandingViewController: UIViewController {
#IBOutlet weak var yearLabel: UILabel!
#IBOutlet weak var firstLabel: UILabel!
#IBOutlet weak var secondLabel: UILabel!
#IBOutlet weak var thirdLabel: UILabel!
#IBOutlet weak var fouthLabel: UILabel!
#IBOutlet weak var fifthLabel: UILabel!
var standing = ""
let standingDataModel = WeatherDataModel()
var currentUrl = ""
let SEASON_URL = "https://ergast.com/api/f1"
//let format = ".json"
override func viewDidLoad() {
super.viewDidLoad()
yearLabel.text = standing
userEnteredNewYear(standing: standing)
// Do any additional setup after loading the view.
}
//MARK: - Networking
/***************************************************************/
//Write the getStandingData method here:
func getStandingData (url: String) {
Alamofire.request(url, method: .get).responseJSON {
response in
if response.result.isSuccess {
print("Success we got the data!")
let standingJSON : JSON = JSON(response.result.value!)
print(standingJSON)
self.updateStandingData(json: standingJSON)
} else {
print("Error \(String(describing: response.result.error))")
self.yearLabel.text = "Connection Issues"
}
}
}
//Mark: JSON Parsing
func updateStandingData(json: JSON) {
if case standingDataModel.season = json["MRData"]["StandingsTable"]["season"].intValue {
standingDataModel.firstDriver = json["DriverStandings"][0]["Driver"]["driverId"].stringValue
updateUIWithStandingData()
} else {
yearLabel.text = "No data available"
}
}
//Mark user entered data.
func userEnteredNewYear(standing: String) {
currentUrl = SEASON_URL + "/" + String(standing) + "/driverstandings.json"
getStandingData(url: currentUrl)
}
func updateUIWithStandingData() {
yearLabel.text = "\(standingDataModel.season)"
firstLabel.text = standingDataModel.firstDriver
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}

I'd recommend ditching SwiftyJSON. Create real model objects instead and use Swift's built-in Codable:
struct F1Data: Codable {
let mrData: MRData
enum CodingKeys: String, CodingKey {
case mrData = "MRData"
}
}
struct MRData: Codable {
let xmlns: String
let series: String
let url: String
let limit, offset, total: String
let standingsTable: StandingsTable
enum CodingKeys: String, CodingKey {
case xmlns, series, url, limit, offset, total
case standingsTable = "StandingsTable"
}
}
struct StandingsTable: Codable {
let season: String
let standingsLists: [StandingsList]
enum CodingKeys: String, CodingKey {
case season
case standingsLists = "StandingsLists"
}
}
struct StandingsList: Codable {
let season, round: String
let driverStandings: [DriverStanding]
enum CodingKeys: String, CodingKey {
case season, round
case driverStandings = "DriverStandings"
}
}
struct DriverStanding: Codable {
let position, positionText, points, wins: String
let driver: Driver
let constructors: [Constructor]
enum CodingKeys: String, CodingKey {
case position, positionText, points, wins
case driver = "Driver"
case constructors = "Constructors"
}
}
struct Constructor: Codable {
let constructorId: String
let url: String
let name: String
let nationality: String
}
struct Driver: Codable {
let driverId: String
let url: String
let givenName, familyName, dateOfBirth, nationality: String
}
do {
let f1Data = try JSONDecoder().decode(F1Data.self, from: jsonData)
let season = f1Data.mrData.standingsTable.season
let firstDriver = f1Data.mrData.standingsTable.standingsLists[0].driverStandings[0].driver.driverId
} catch {
print(error)
}

Related

How to decode custom type inside dictionary value with JSON?

my JSON:
https://www.cbr-xml-daily.ru/daily_json.js
my code:
struct CoinData: Decodable {
let Valute: [String: CoinInfo]
}
struct CoinInfo: Decodable {
let Name: String
let Value: Double
}
if let safeData = data {
if let coinData = self.parseJSON(safeData) {
print(coinData)
}
}
func parseJSON(_ data: Data) -> [String: CoinInfo]? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(CoinData.self, from: data)
return decodedData.Valute
} catch {
delegate?.didFailWithError(error: error)
return nil
}
}
In debug console following gets printed:
["PLN": CurrencyConverter.CoinInfo(Name: "X", Value: 19.6678), ...]
This way I can't reach Name and Value properties of a coin. What's wrong?
I am going to do for-loop to check if a key contains certain symbols. If it does - I will need to be able to access to both Name and Value
You don't actually need a for loop. Since coinData is a dictionary, you can use its subscript, together with optional binding to do this. For example, to check if the key "PLN" exists, and access its name and value:
if let coinInfo = coinData["PLN"] {
print(coinInfo.Name)
print(coinInfo.Value)
} else {
// "PLN" does not exist
}
StoyBoard
Code
import UIKit
import Alamofire
// MARK: - CoinData
struct CoinData: Codable {
let date, previousDate: String
let previousURL: String
let timestamp: String
let valute: [String: Valute]
enum CodingKeys: String, CodingKey {
case date = "Date"
case previousDate = "PreviousDate"
case previousURL = "PreviousURL"
case timestamp = "Timestamp"
case valute = "Valute"
}
}
// MARK: - Valute
struct Valute: Codable {
let id, numCode, charCode: String
let nominal: Int
let name: String
let value, previous: Double
enum CodingKeys: String, CodingKey {
case id = "ID"
case numCode = "NumCode"
case charCode = "CharCode"
case nominal = "Nominal"
case name = "Name"
case value = "Value"
case previous = "Previous"
}
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
var getCoinData = [CoinData]()
var coinNameArr = [String]()
var coinDataArr = [Valute]()
#IBOutlet weak var tblDataList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
getData()
}
func getData()
{
let url = "https://www.cbr-xml-daily.ru/daily_json.js"
AF.request(url, method: .get, encoding: URLEncoding.default).responseJSON { response in
let json = response.data
do{
let decoder = JSONDecoder()
self.getCoinData = [try decoder.decode(CoinData.self, from: json!)]
let response = self.getCoinData[0]
if response.valute.count != 0 {
self.coinNameArr.removeAll()
self.coinDataArr.removeAll()
for (coinName, coinData) in response.valute {
self.coinNameArr.append(coinName)
self.coinDataArr.append(coinData)
}
self.tblDataList.reloadData()
} else {
}
}catch let err{
print(err)
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return coinDataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:coinTblCell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath as IndexPath) as! coinTblCell
cell.accessoryType = .disclosureIndicator
cell.tintColor = .black
let rowData = coinDataArr[indexPath.row]
cell.lblName.text = rowData.name
cell.lblValue.text = String(rowData.value)
return cell
}
}
class coinTblCell: UITableViewCell {
#IBOutlet weak var lblName: UILabel!
#IBOutlet weak var lblValue: UILabel!
}

Assign json data to labels

I'm beginner in swift programming and I want to assign the data to labels
so I have this code below
#IBOutlet weak var Infected: WKInterfaceLabel!
#IBOutlet weak var Cured: WKInterfaceLabel!
#IBOutlet weak var Deaths: WKInterfaceLabel!
#IBOutlet weak var OmanInfected: WKInterfaceLabel!
#IBOutlet weak var OmanCured: WKInterfaceLabel!
#IBOutlet weak var OmanDeaths: WKInterfaceLabel!
func check()
{
// MARK: - CoronaData
struct CoronaData: Codable {
var countrydata: [Countrydatum]
var stat: String
}
// MARK: - Countrydatum
struct Countrydatum: Codable {
var info: Info
var totalCases, totalRecovered, totalUnresolved, totalDeaths: Int
var totalNewCasesToday, totalNewDeathsToday, totalActiveCases, totalSeriousCases: Int
var totalDangerRank: Int
enum CodingKeys: String, CodingKey {
case info
case totalCases = "total_cases"
case totalRecovered = "total_recovered"
case totalUnresolved = "total_unresolved"
case totalDeaths = "total_deaths"
case totalNewCasesToday = "total_new_cases_today"
case totalNewDeathsToday = "total_new_deaths_today"
case totalActiveCases = "total_active_cases"
case totalSeriousCases = "total_serious_cases"
case totalDangerRank = "total_danger_rank"
}
}
// MARK: - Info
struct Info: Codable {
var ourid: Int
var title, code: String
var source: String
}
if let url = URL(string: "https://api.thevirustracker.com/free-api?countryTotal=OM") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
let decoder = JSONDecoder()
let gitData = try decoder.decode(Countrydatum.self, from: data)
print(gitData.totalCases as Any)
} catch let error {
print(error)
}
}
}.resume()
}
}
how can I now assign these values to the labels here (Num labels)
I know this is a stupid question to ask but forgive me for that
I just want to finish the program and learn some new things
You can download this free program to make the struct
see this example to use the struct
if let url = URL(string: "https://api.thevirustracker.com/free-api?countryTotal=OM") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
let decoder = JSONDecoder()
let profile = try decoder.decode(ProfileResponse.self, from: data)
print(profile.countrydata.first)
} catch let error {
print(error)
}
}
}.resume()
}
You can change the text programmatically using the setText(:) or setAttributedText(:) method.
I replicate the request in Playground the text is different bus the way that you need to access the data is the same, country data is an array so you need to get the first element
import UIKit
import PlaygroundSupport
// MARK: - ProfileResponse
struct ProfileResponse: Codable {
var countrydata: [ProfileCountrydatum]
var stat: String
}
// MARK: - ProfileCountrydatum
struct ProfileCountrydatum: Codable {
var info: ProfileInfo
var totalCases, totalRecovered, totalUnresolved, totalDeaths: Int
var totalNewCasesToday, totalNewDeathsToday, totalActiveCases, totalSeriousCases: Int
var totalDangerRank: Int
enum CodingKeys: String, CodingKey {
case info
case totalCases = "total_cases"
case totalRecovered = "total_recovered"
case totalUnresolved = "total_unresolved"
case totalDeaths = "total_deaths"
case totalNewCasesToday = "total_new_cases_today"
case totalNewDeathsToday = "total_new_deaths_today"
case totalActiveCases = "total_active_cases"
case totalSeriousCases = "total_serious_cases"
case totalDangerRank = "total_danger_rank"
}
}
// MARK: - ProfileInfo
struct ProfileInfo: Codable {
var ourid: Int
var title, code: String
var source: String
}
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
view.addSubview(label)
self.view = view
if let url = URL(string: "https://api.thevirustracker.com/free-api?countryTotal=OM") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
let decoder = JSONDecoder()
let gitData = try decoder.decode(ProfileResponse.self, from: data)
label.text = "\(gitData.countrydata.first?.totalDeaths ?? 0)"
} catch let error {
print(error)
}
}
}.resume()
}
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
The countrydata is presented as an array, but the corresponding property in your model is of type String.

How to put data to Label from JSON

I need to put data that I get with JSON to cityLabel, temperatureLabel, weatherLabel for today and tableview where I Have dateLabel, weatherLabel and min and max temperature label for next 5 days. I know that for table view I need also add UITableViewDataSource. On this moment in Simulator I get clean label with nothing.
Code that I have in WeatherForecast.swift
import Foundation
// MARK: - Welcome
struct WeatherForecast: Codable {
let cod: String
let message, cnt: Int
let list: [List]
let city: City
}
// MARK: - City
struct City: Codable {
let id: Int
let name: String
let coord: Coord
let country: String
let population, timezone, sunrise, sunset: Int
}
// MARK: - Coord
struct Coord: Codable {
let lat, lon: Double
}
// MARK: - List
struct List: Codable {
let dt: Int
let main: MainClass
let weather: [Weather]
let clouds: Clouds
let wind: Wind
let sys: Sys
let dtTxt: String
let rain, snow: Rain?
enum CodingKeys: String, CodingKey {
case dt, main, weather, clouds, wind, sys
case dtTxt = "dt_txt"
case rain, snow
}
}
// MARK: - Clouds
struct Clouds: Codable {
let all: Int
}
// MARK: - MainClass
struct MainClass: Codable {
let temp, feelsLike, tempMin, tempMax: Double
let pressure, seaLevel, grndLevel, humidity: Int
let tempKf: Double
enum CodingKeys: String, CodingKey {
case temp
case feelsLike = "feels_like"
case tempMin = "temp_min"
case tempMax = "temp_max"
case pressure
case seaLevel = "sea_level"
case grndLevel = "grnd_level"
case humidity
case tempKf = "temp_kf"
}
}
// MARK: - Rain
struct Rain: Codable {
let the3H: Double
enum CodingKeys: String, CodingKey {
case the3H = "3h"
}
}
// MARK: - Sys
struct Sys: Codable {
let pod: Pod
}
enum Pod: String, Codable {
case d = "d"
case n = "n"
}
// MARK: - Weather
struct Weather: Codable {
let id: Int
let main: MainEnum
let weatherDescription, icon: String
enum CodingKeys: String, CodingKey {
case id, main
case weatherDescription = "description"
case icon
}
}
enum MainEnum: String, Codable {
case clear = "Clear"
case clouds = "Clouds"
case rain = "Rain"
case snow = "Snow"
}
// MARK: - Wind
struct Wind: Codable {
let speed: Double
let deg: Int
}
What I get in ViewController.swift by parsing JSON
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var cityNameLabel: UILabel!
#IBOutlet weak var temperatureLabel: UILabel!
#IBOutlet weak var weatherNowLabel: UILabel!
#IBOutlet weak var dailyWeatherTableView: UITableView!
var degreeSymbol = "ยบ"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
currentWeatherRequest()
}
func currentWeatherRequest() {
let session = URLSession.shared
let weatherURL = URL(string: "http://api.openweathermap.org/data/2.5/forecast?q=Atlanta,us?&units=metric&APPID=apikey")!
let dataTask = session.dataTask(with: weatherURL) { (data: Data?,response: URLResponse?,error: Error?) in
if let error = error {
print("Error:\n\(error)")
} else {
if let data = data {
do {
let dataString = String(data: data, encoding: String.Encoding.utf8)
print("Daily weather data:\n\(dataString!)")
let decoder = JSONDecoder()
let responseModel = try decoder.decode(WeatherForecast.self, from: data)
print(responseModel)
// } else {
// print("Error: unable to convert json data")
// }
} catch let error {
print("Error: \(error)")
}
}else {
print("Error: did not receive data")
}
}
}
dataTask.resume()
}
func weatherDetails(){
print(City.self)
}
/* func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
<#code#>
}*/
}
You can assign values to your labels after API Manager gets the values below
let responseModel = try decoder.decode(WeatherForecast.self, from: data)
print(responseModel)
by saying for example : cityNameLabel.text = responseModel.city.name
For the tableView make sure to set dailyWeatherTableView delegate and datasource using storyBoard or programmatically in view didload by writing
dailyWeatherTableView.delegate = self
dailyWeatherTableView.dataSource = self

Cannot assign value of type 'MRData' to type '[F1Data]' when trying to parse JSON

I have been wrestling with this for a while. I am trying to parse a JSON Api into a UITableview. The url is Formula One API . I am using Codable rather than third party pods. Thought this might cut down on the amount of code. Although, as the API is not that straight forward it is hard to extract what I want. Basically, I want to list the current standing for drivers for a given year. In url and code I have given I have chosen 1999 as an example. I have been researching on Stackoverflow but each solution is very specific to a particular problem and I can't seem to relate to my issue. Below is the code I have.
struct MRData: Codable {
let xmlns: String?
let series: String?
let url: String?
let limit, offset, total: String?
let standingsTable: StandingsTable
enum CodingKeys: String, CodingKey {
case xmlns, series, url, limit, offset, total
case standingsTable = "StandingsTable"
}
}
struct StandingsTable: Codable {
let season: String?
let standingsLists: [StandingsList]
enum CodingKeys: String, CodingKey {
case season
case standingsLists = "StandingsLists"
}
}
struct StandingsList: Codable {
let season, round: String?
let driverStandings: [DriverStanding]
enum CodingKeys: String, CodingKey {
case season, round
case driverStandings = "DriverStandings"
}
}
struct DriverStanding: Codable {
let position, positionText, points, wins: String?
let driver: Driver
let constructors: [Constructor]
enum CodingKeys: String, CodingKey {
case position, positionText, points, wins
case driver = "Driver"
case constructors = "Constructors"
}
}
struct Constructor: Codable {
let constructorId: String?
let url: String?
let name: String?
let nationality: String?
}
struct Driver: Codable {
let driverId: String?
let url: String?
let givenName, familyName, dateOfBirth, nationality: String?
}
class f1TableViewController: UITableViewController {
var champions: [F1Data] = []
override func viewDidLoad() {
super.viewDidLoad()
// let jsonUrlString = "https://api.letsbuildthatapp.com/jsondecodable/website_description"
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Champion Drivers"
fetchJSON()
}
private func fetchJSON(){
let jsonUrlString = "https://ergast.com/api/f1/1999/driverstandings.json"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
DispatchQueue.main.async {
if let err = err {
print("Failed to get data from url:", err)
return
}
guard let data = data else { return }
do {
let decoder = JSONDecoder()
// Swift 4.1
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.champions = try decoder.decode(MRData.self, from: data)
self.tableView.reloadData()
//let season = f1Data.mrData.standingsTable.season
// let firstDriver = f1Data.mrData.standingsTable.standingsLists[0].driverStandings
// for driver in firstDriver {
//
// print("\(driver.driver.givenName) \(driver.driver.familyName)")
// }
//print(season)
} catch {
print(error)
}
}
}.resume()
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return champions.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId")
let champion = champions[indexPath.row]
let driverName = champion.mrData.standingsTable.standingsLists[0].driverStandings
for driver in driverName {
cell.textLabel?.text = driver.driver.familyName
}
//cell.textLabel?.text =
//cell.detailTextLabel?.text = String(course.numberOfLessons)
return cell
}
}
Now I realize that the error is in the do catch block.
do {
let decoder = JSONDecoder()
// Swift 4.1
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.champions = try decoder.decode(MRData.self, from: data)
self.tableView.reloadData()
and that the array F1Data cannot be a dictionary of MRData. So if I change it to the following self.champions = try decoder.decode([F1Data].self, from: data) the I get another error which is
debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil)). Any help would be appreciated with this.
As Vadian correctly said that you need to decode at the root of your object. I briefly watched this video and the penny dropped! Assign the decoder to a variable and add to decode the complete structure starting at the root object.
guard let data = data else { return }
do {
let decoder = JSONDecoder()
// Swift 4.1
decoder.keyDecodingStrategy = .convertFromSnakeCase
let firstDriver = try decoder.decode(F1Data.self, from: data)
self.champions = firstDriver.mrData.standingsTable.standingsLists[0].driverStandings
self.tableView.reloadData()

Why isn't my text being added to my label?

Revised post: So the code posted below is my stuct
struct AnimeJsonStuff: Decodable {
let data: [AnimeDataArray]
}
struct AnimeLinks: Codable {
var selfStr : String?
private enum CodingKeys : String, CodingKey {
case selfStr = "self"
}
}
struct AnimeAttributes: Codable {
var createdAt : String?
var slug : String?
private enum CodingKeys : String, CodingKey {
case createdAt = "createdAt"
case slug = "slug"
}
}
struct AnimeRelationships: Codable {
var links : AnimeRelationshipsLinks?
private enum CodingKeys : String, CodingKey {
case links = "links"
}
}
struct AnimeRelationshipsLinks: Codable {
var selfStr : String?
var related : String?
private enum CodingKeys : String, CodingKey {
case selfStr = "self"
case related = "related"
}
}
struct AnimeDataArray: Codable {
let id: String?
let type: String?
let links: AnimeLinks?
let attributes: AnimeAttributes?
let relationships: [String: AnimeRelationships]?
private enum CodingKeys: String, CodingKey {
case id = "id"
case type = "type"
case links = "links"
case attributes = "attributes"
case relationships = "relationships"
}
}
This code is my function for parsing data:
func jsonDecoding() {
let jsonUrlString = "https://kitsu.io/api/edge/anime"
guard let url = URL(string: jsonUrlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
do {
let animeJsonStuff = try JSONDecoder().decode(AnimeJsonStuff.self, from: data)
for anime in animeJsonStuff.data {
// print(anime.id)
// print(anime.type)
// print(anime.links?.selfStr)
let animeName = anime.attributes?.slug
print(animeName)
DispatchQueue.main.async {
self.nameLabel.text = animeName
}
for (key, value) in anime.relationships! {
// print(key)
// print(value.links?.selfStr)
// print(value.links?.related)
}
}
} catch let jsonErr {
print("Error serializing json", jsonErr)
}
}.resume()
}
This is what the console prints out:
Optional("cowboy-bebop")
Optional("cowboy-bebop-tengoku-no-tobira")
Optional("trigun")
Optional("witch-hunter-robin")
Optional("beet-the-vandel-buster")
Optional("eyeshield-21")
Optional("honey-and-clover")
Optional("hungry-heart-wild-striker")
Optional("initial-d-fourth-stage")
Optional("monster")
Optional("cowboy-bebop")
Optional("cowboy-bebop-tengoku-no-tobira")
Optional("trigun")
Optional("witch-hunter-robin")
Optional("beet-the-vandel-buster")
Optional("eyeshield-21")
Optional("honey-and-clover")
Optional("hungry-heart-wild-striker")
Optional("initial-d-fourth-stage")
Optional("monster")
Optional("cowboy-bebop")
Optional("cowboy-bebop-tengoku-no-tobira")
Optional("trigun")
Optional("witch-hunter-robin")
Optional("beet-the-vandel-buster")
Optional("eyeshield-21")
Optional("honey-and-clover")
Optional("hungry-heart-wild-striker")
Optional("initial-d-fourth-stage")
Optional("monster")
It now displays the text but it only displays the last optional called monster and not all the other ones when I have three cells. It only displays monster in each cell.
It should be
1st cell: Cowboy-bebpop
2nd cell: cowboy-bebop-tengoku-no-tobira
3rd cell: trigun
and etc
I can't see where do you set post variable.
Where you put nambeLabel into Controller's view hierarchy?
And maybe you should set nameLabel.text in main thread:
DispatchQueue.main.async {
self.nameLabel.attributedText = attributedText
}