ios - Handle populating a tableview with asynchronous API calls -
i have 2 objects. note
, user
.
public class note { var userid: int var createdatdate: nsdate var content: string? init(userid: int, createdatdate: nsdate) { self.userid = userid self.createdatdate = createdatdate } } public class user { var id: int var firstname: string var lastname: string var email: string var avatar: uiimage? init(id: int, firstname: string, lastname: string, email: string) { self.id = id self.firstname = firstname self.lastname = lastname self.email = email } }
and there 2 api methods. 1 list out notes. json response get.
{ "status": "success", "data": [ { "user_id": 2, "note": "this test\r\n\r\nthis test.\r\n\r\nbeep boop", "created_at": "2015-07-29 04:39:25" } ] }
note user's id in response. user details (first name ,last name etc), there's api call. when pass user id, gives user's details. json response.
{ "status": "success", "data": { "id": 2, "email": "dev@example.com", "first_name": "john", "last_name": "appleseed", "avatar": "avt.png" } }
note both these api methods return results asynchronously. brings me issue.
i need display these notes in section-ed tableview each note's user's full name in footer.
the problem since user detail api call asynchronous, happens in different thread , takes time receive results. loading notes tableview happens separately can't figure out how map each note's user when user's detail arrives.
func tableview(tableview: uitableview, titleforfooterinsection section: int) -> string? { let note = notes[section] apiclient.getuserdetails(id: id, success: { (data) -> void in }) { (error) -> void in } return "" }
for example, let's take first note in notes
array. gets userid
of note , pass getuserdetails
method retrieve user details. since async, tableview won't wait until receives user's details. time that, might have moved on note , spinning off async calls on place!
anyone got idea how tackle situation?
the approach solve might you.
you fire second request (getuserdetails) in success block of first api call. (or whichever method/delegate using handle receiving data server)
on success of second request, reload table show appropriate data
since takes time show details add activity indicator , hide table till receive required data server.
i assuming using separate block or delegate job of handling data response server.
if strategically place server requests on success handling methods, 1 after other, though data interlinked , calls asynchronous - synchronous-like flow.
hope helps!
Comments
Post a Comment