【发布时间】:2020-07-01 14:17:33
【问题描述】:
我有 UITableViewController,我正在尝试从 url 解析数据, 始终捕获正在执行的语句,该语句在控制台中打印“某事”。 在 Storyboard 中,我将重用标识符添加到表格视图单元格中。
''' 类 TableViewController: UITableViewController {
final let url = URL(string: "http://jsonplaceholder.typicode.com/posts")
private var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
downloadJson()
}
func downloadJson() {
guard let downloadURL = url else { return }
URLSession.shared.dataTask(with: downloadURL) { (data, response, error) in
guard let data = data, error == nil, response != nil else {
return
}
do {
let decoder = JSONDecoder()
let tempPosts = try decoder.decode(Posts.self, from: data)
print(tempPosts)
self.posts = tempPosts.posts
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print("something")
}
}.resume()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = posts[indexPath.row].title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
} '''
'''
class Posts: Codable {
let posts: [Post]
init(posts: [Post]) {
self.posts = posts
}
}
class Post: Codable {
let userId: Int
let id: Int
let title: String
let body: String
init(userId: Int, id: Int, title: String, body: String) {
self.userId = userId
self.id = id
self.title = title
self.body = body
}
} '''
【问题讨论】:
-
print("something")=>print("Error while parsing: \(error)")。这是第一步(也是重要的一步)。 -
添加您用于解析数据的 JSON 响应和 Posts 模型
-
在看到 URL 上的 JSON 之后,我猜是
decoder.decode(Posts.self, from: data)=>decoder.decode([Posts].self, from: data),但这是推测。我们也需要Posts代码,因为可能还有其他问题。 -
我已将模型添加到问题中
标签: json swift uitableview parsing cell