简体   繁体   中英

How i implement my JSON API Request into a UITableViewCell?

I have a problem with my current Project. First of all, i like to implement a JSON API Request that allows me to get a title off a URL. The Problem: I want to display the JSON data into a UITableViewCell .

But Xcode throws following Error:

Cannot assign value of type 'FirstViewController.Title' to type 'String?'

Maybe there is more wrong in my code, because i'm just a beginner at Swift/Xcode

I already tried this:

cell.textLabel?.text = course.title as? String

But i got warning message as follows:

Cast from 'FirstViewController.Title' to unrelated type 'String' always fails

This is my code sample:

var courses = [Course]()
let cell = "ItemCell"

override func viewDidLoad() {
    super.viewDidLoad()

    fetchJSON()
}

struct Course: Codable {
    let title: Title

    enum CodingKeys: String, CodingKey {
        case title
        case links = "_links"
    }
}

struct Links: Codable {
}

struct Title: Codable {
    let rendered: String
}


fileprivate func fetchJSON() {
    let urlString = "ExampleURL"
    guard let url = URL(string: urlString) else { return }
    URLSession.shared.dataTask(with: url) { (data, _, 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 result = try JSONDecoder().decode(Course.self, from: data)


                self.tableView.reloadData()
            } catch let jsonErr {
                print("Failed to decode:", jsonErr)
            }
        }
        }.resume()
}

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .value1, reuseIdentifier: "ItemCell")
    let course = courses[indexPath.row]
    cell.textLabel?.text = course.title as? String // Cast from 'FirstViewController.Title' to unrelated type 'String' always fails
    return cell
}

I just want to get WordPress posts into a UITableView - UITableViewCell .

Maybe you can tell me if its the wrong way i tried it but i don't really know how i solve this problem

Thank you in advance

Assign the var before the reload

 let res = try JSONDecoder().decode(Course.self, from: data)
 courses.append(res)
 DispatchQueue.main.async {
     self.tableView.reloadData()
 }

And set it to the string value

 cell.textLabel?.text = course.title.rendered

 courses = try JSONDecoder().decode([Course].self, from: data)
 print(courses)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM