简体   繁体   中英

parsing nested arrays to populate uitableview in swift

This is the API response which I have parsed

{
"status": 0,
"message": "Friends found.",
"friends": [
    {
        "id": 52,
        "meetings": [
            {
                "id": 47,
                "meeting_with": "Bbb"
            }
        ]
    }
]
}

The model class

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
}

Im calling the API here and the call is successful.

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
}

Please guide me how do I populate the tableview with the response coming from API call.

  1. you have to declared array instance of type according to your need either FriendDetail or MeetingsDetail.

  2. After fetching data from api parse it and store mapped data into an array instance. Then, reload table view.

  3. numberOfRowsInSection method of tableview returns number of rows using your array count.

  4. You can access value by using dot notation as shown in "cellForRowAt indexPath:" method.

     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 } }

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