请帮助解决以下代码在从下面给定的 url 调用 api 时出错
导入 UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView : UITableView!
var userDetails : User?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UsersTableViewCell.NIB, forCellReuseIdentifier: UsersTableViewCell.identifier)
getData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userDetails?.first_name.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: UsersTableViewCell.identifier) as! UsersTableViewCell
cell.fistLbl = userDetails?.first_name[indexPath.row]
return cell
}
private func getData() {
let url = "https://reqres.in/api/users?page=1"
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { [self]data , response , error in
guard let data = data , error == nil else {
return print("Something Went wrong")
}
do {
userDetails = try JSONDecoder().decode(User.self, from: data)
}
catch {
print(error.localizedDescription)
}
guard let json = userDetails else {return}
print(json.first_name)
print(json.last_name)
print(json.avatar)
})
task.resume()
}
}
struct User: Codable {
let avatar: String
let first_name: String
let last_name: Int
}