0

I am building an app that presents UITableView to the user, from which the user needs to make a selection. Once the selects a row, they are presented another ViewController which displays details of the selection they made on the previous ViewController.

Here's the catch: After the user makes the selection, the app needs to make a call to the network to retrieve some data to be displayed on the next ViewController. I was planning on calling a method from the prepareForSegue method which would return the results from the network call, and then call the appropriate ViewController, but I'm wondering if this is something that should be called from the "didSelectRowAtIndexPath" method (which I have not implemented).

My fear is that the second ViewController will be called BEFORE the call to the network returns with the data that I need to display. Is this even the place to put such a network call, or should I make this call from the "viewDidLoad" method of the destination ViewController instead? What is the best architecture and why?

halfer
  • 19,824
  • 17
  • 99
  • 186
syedfa
  • 2,801
  • 1
  • 41
  • 74

2 Answers2

1

Call prepareForSegue method inside didSelectRowAtIndexPath method to navigate to secondViewController then to display details, make network call inside viewDidLoad method of secondViewController and show activityIndicatorView until the data is fetched.

Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22
1

I would use some asynchronous loading starting in prepareForSegue and managed in the details view. Once the details view appears, you have to inform user that something is loading (an appropriate turning wheel exists for it), and then populate the interface after the loading has been done (or manage loading error).

But using viewDidLoad of the details view would be ok too, provided you always inform user of the current loading...

Don't use didSelectRow because it is just intended for selection... There can be no navigation on a tableview cell!

Asynchronous is preferred because it does not block user in some weird state waiting something he does really know.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • I agree with you that the call must be asynchronous. My question is, where should this call be made, didSelectRowAtIndexPath, prepareForSegue, or viewDidLoad? The approach I'm leaning towards is to make the call from didSelectRowAtIndexPath, and build my object with the results, and pass it on to my prepareForSegue method, which hands off the object to the detailViewController. Your thoughts? – syedfa Apr 04 '17 at 15:28
  • I told you, `didSelectRowAtIndexPath` is not intended for that, because selecting doesn't implies going to detail view... So either `prepareForSegue` or `viewDidLoad`. – Jean-Baptiste Yunès Apr 05 '17 at 11:35