First of all it's highly recommended to drop SwiftyJSON
in favor of Codable
.
Nevertheless just create a data source array, assign the received data to the data source array and reload the table view. In cellForRow
get the item from the array and assign the values to the corresponding UI elements
var data = [JSON]()
func getUsers() {
AF.request(SiteUrl).validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful)")
if let json = response.data {
do{
let jsonData = try JSON(data: json)
self.data = jsonData.arrayValue
self.tableView.reloadData() // we are already on the main thread
print("DATA PARSED: (jsonData)")
}
catch {
print("JSON Error", error)
}
}
case .failure(let error):
print(error)
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let item = data[indexPath.row]
cell.textLabel?.text = item["user_id"].string
return cell
}
And this is the modern way, first create a struct (you have to add the other members according to the JSON and use camelCase names: "user_id" -> userId
)
struct User : Decodable {
let id, contactName : String
let userId : String
}
and replace the other code above with
var users = [User]()
func getUsers() {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
AF.request(SiteUrl).validate().responseDecodable(decoder: decoder) { (response : DataResponse<[User],AFError>) in
switch response.result {
case .success(let result):
print("Validation Successful)")
self.users = result
self.tableView.reloadData()
case .failure(let error): print("JSON Error", error)
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let user = users[indexPath.row]
cell.textLabel?.text = user.userId
return cell
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…