uchicago-mobi / MPCS51030-2017-Winter-Forum

7 stars 0 forks source link

Main Thread vs Background Thread #148

Closed hbennett766 closed 7 years ago

hbennett766 commented 7 years ago

Repeated issue, figured I'd make a note of it in case anyone is running into the following problem(s):

collection view not reloading activity indicator not showing up activity indicator not going away alert controller not showing up something else the user is supposed to see but doesn't

The project for this week is very "data grab"-centric. There are a lot of network calls happening, and things being fetched from various places. Best practice is to do this on a background thread, because otherwise it would lock up the main thread (freeze the screen) while it was occupied with things the user can't see. This would be a bad user experience. Lucky for us, iOS does a lot of this for us. Data tasks and other things like this just get sent to background threads automatically, so developers don't have to worry about it.

However, anything that is UI related should be done on the main thread. This means that when you say "hey go grab data", you should start animating your activity indicator outside/above the data task block, before things get sent to background threads. This also means that when you get your data back from a network call, and need to stop animating an activity indicator, reload your table data, etc, you may need to go grab the main thread and manually place these tasks on it. The code to do this is pretty simple:

DispatchQueue.main.async { // do all UI related tasks on the main thread }

Here's a walkthrough on threading in Swift 3: https://www.raywenderlich.com/148513/grand-central-dispatch-tutorial-swift-3-part-1

Will you need to manually set things on certain threads often? Probably not. Will bad things happen if you try and update the UI on a background thread? Probably.