这是我已解析的API响应
{
"status": 0,
"message": "Friends found.",
"friends": [
{
"id": 52,
"meetings": [
{
"id": 47,
"meeting_with": "Bbb"
}
]
}
]
}
模型类
struct TotalMeetings: Decodable {
var status: Int
var message: String
var friends: [FriendDetail]?
}
struct FriendDetail: Decodable {
var id: Int
var meetings: [MeetingsDetail]
}
struct MeetingsDetail: Decodable {
var id: Int
var meeting_with: String
}
我在这里调用API,调用成功。
var meetingssData :Friends!
let decoder = JSONDecoder()
do{
meetingsData = try decoder.decode(TotalMeetings.self, from: response.data!)
let meet = [self.meetingsData!.friends].compactMap({$0}).flatMap({$0})
print(meetingsData!)
}catch{
print(error)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FriendsMeetingTVC
return cell
}
请指导我如何使用来自API调用的响应填充表格视图。
答案 0 :(得分:0)
您必须根据需要声明类型的数组实例FriendDetail或MeetingsDetail。
从api提取数据后,将其解析并将映射的数据存储到数组实例中。然后,重新加载表格视图。
numberOfRowsInSection 方法使用您的数组计数返回行数。
您可以使用点表示法来访问值,如“ cellForRowAt indexPath:” 方法中所示。
class MeetingVC: UIViewController, UITableViewDelegate, UITableViewDatasource {
var friendsArr = [FriendDetail]()
func fetchFriendDetail() {
let decoder = JSONDecoder()
do {
let meetingsData = try decoder.decode(TotalMeetings.self, from: response.data!)
self.friendsArr = meetingsData.friends ?? []//[meetingsData.friends].compactMap({$0}).flatMap({$0})
print(self.friendsArr)
self.tableView.reloadData()
}catch{
print(error)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friendsArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FriendsMeetingTVC
cell.emailTxt.text = friendsArr[indexPath.row].email
return cell
}
}