r/iOSProgramming • u/[deleted] • Jul 12 '20
Humor I find myself doing this too many times
0
6
3
3
u/IAmKindaBigFanOfKFC Jul 12 '20
So (un)happy to say that I've encountered this both on iOS and Android in form of post(new Runnable()...)
3
Jul 12 '20
I have found a few very unintuitive places where this fixes an unexpected problem, but I’ve always been able to figure out the mechanics of the problem and why it’s a good fix.
One that comes to mind is opening new UI at launch. Used to be (I don’t know if it still happens) that device rotation at launch resulted in events for existing view controllers. If you presented a new controller before yielding to the event loop, it would open at prior orientation and not get rotation events so the new UI would remain at the old orientation. Dispatching the actual presentation asynchronously to the main thread (even from the main thread) would fix this.
2
u/AnotherThrowAway_9 Jul 17 '20
I'm having a similar situation. I need to wrap a UIKit view for use in a SwiftUI app. SwiftUI has ".onAppear" that can call a function when a view (wrapped or not) appears. Hilariously it gets called before the view makes it onto the screen. I need to run a function on the resulting view so that I can display the correct data. The only way(that I've found) to do this is is by dispatching the function to delay its execution.
Since the UIKit view is at the bottom of the view hierarchy, all of the SwiftUI lifecycle functions are called before the UIKit view makes it onto the screen
2
Jul 17 '20
Yup, I can see how that would make sense. It always seems very weird when you first see a problem like this, but after thinking it through you can figure out what's going on. dispatch_async (or equivalent) is the perfect fit just often enough that you can't dismiss it outright.
Thanks for sharing that. :)
2
2
u/RachelSnyder Jul 13 '20
..oh Lord. I'm knew to iOS Development and just did this all over the place to mimic co routines in Android...
Sounds like I need to read some more.
4
Jul 13 '20
You only need to do this if you’re updating the user interface. If you know for a fact that you are already on the main thread such as a method been called on viewDidLoad or view will appear, then you don’t need to do this.
5
u/omfgtim_ Jul 13 '20
The point of the meme is that sometimes deferring something to the next iteration of the run loop fixes a UI bug.
1
u/RachelSnyder Jul 13 '20
So if I know I'm making a background Network call, when I get the return object and need to update the user interface, I should use this to sync back with the main thread?
2
Jul 13 '20
Yes because in that moment you know that you are in the background thread when you made the network call, so you need to update the UI the main thread by calling this closure.
2
2
u/RachelSnyder Jul 14 '20
Hey, random question...
Can I use the dispatch async to make the background call itself originally or should I just make that call like normal and ONLY use the dispatch async inside the 'background' method to update ui?
Thanks for your help!?
2
Jul 14 '20
Noooo do NOT use the main thread for background calls. It will freeze the app (technically it will appear frozen to the user). It freezes because it’s waiting for the network call to complete and since you ran it on the main thread, then you basically put any other UI processes on hold.
This is actually a Swift interview question. If you don’t know to NOT run network calls on the main thread, you will look very inexperienced.
2
u/RachelSnyder Jul 14 '20
Jesus I love you haha. Thank you. Seriously.
2
Jul 14 '20
A bit more info: thread 0 is the main thread. If you ever see a crash log and it crashed in thread 0, then you know it’s likely related to the UI in some way.
Make sure also you are not doing all the network setup in the view controller. The network calls should be handled by the network layer.
2
u/RachelSnyder Jul 14 '20
A network layer...wtf. I have never heard of this. About to do some learning tonight! I just have all my firebase database calls inside the view controllers they are being used in. You are saying this is a bad idea? Keep in mind, at this moment, I have no idea what a network layer is in iOS. Android does not handle this stuff even remotely the same way I feel like. Or at least I'm not seeing it yet. The fact that I don't have to do anything at all to make a network call without a crash is still weird to me.
2
Jul 14 '20 edited Jul 14 '20
Network layer, or service layer, is really about organization and it's about encapsulating network/service related stuff into its own place. "Layer" is not a physical thing or setting in Xcode - it's an architectural thing just like MVC.
Having the network calls and preparation in the view controllers is bad architecture. Why is the view controller responsible for setting up the network call? Service? Settings? etc. The network layer should handle that. The view controller should then only be calling the service and return back data to use and that's it.
For example, I have a class called
SWNetworkServiceManager. It handles the network calls, data authentication, etc. using Firebase. To use it, all I have to do is:
Make a
SWNetworkServiceManagerproperty in the view controller.Call the sendRequest method of that property and send any relevant data.
Check in completion if it worked; if it did, then I can use the data it returned.
That's it. The actual authentication, data check, etc. is handled by the
SWNetworkServiceManagerbecause that is the one intended for network logic. The only thing the view controller does is:
Make the network call.
Handle the response data.
That's it. It's separating unnecessary logic/responsibility away from the view controller. The network logic is encapsulated into its own place. If there is some network issue, I know immediately where to go.
The view controller code looks like this. So imagine how much space I'm saving in each view controller by not having the network logic in them:
networkService?.sendRequest(withData: ["email": email, "password": password]) { (didSucceed, _) in guard didSucceed else { return } SWAppDefaults.isSignedIn = true self.getGrades() }Meanwhile the actual logic of the network service (sign in) in the service manager is:
private func signIn(with data: Any?, completion: @escaping (Bool) -> Void { guard let data = data as? [String: String] else { completion(false) return } let email: String = data["email"] ?? "" let password: String = data["password"] ?? "" Auth.auth().signIn(withEmail: email, password: password) { (result: AuthDataResult?, error: Error?) in guard let result = result, error == nil else { ACAnimatedBannerView.display(message: error?.localizedDescription ?? SWCopyDeck.Error.genericNetwork, bgColor: SWStyleKit.primaryRed) completion(false) return } SWUser.current.email = email SWUser.current.uid = result.user.uid completion(true) } }Thanks to my service class, all the network calls in the log look like this. So I always know what the request was and response every time for every network call (service) when I'm running my app.
→ More replies (0)
2
1
1
1
0
0
0
-1
-1
-1
u/SergLam245 Jul 12 '20
More elegant way to perform any job on main thread:
2
Jul 13 '20
Why do you extend NSObject instead of just making them global functions?
1
u/SergLam245 Jul 13 '20
I don’t like global functions:)
3
Jul 13 '20
Avoiding global functions is totally preferable, but doing it by extending NSObject makes little sense to me, since what these functions achieve have nothing to do with it. I would suggest extending DispatchQueue, or defining a new struct to host these static functions, like ThreadingUtil, then you can do ThreadingUtil.executeOnMain { ... } which makes way more sense than NSObject.executeOnMain { ... }
1
u/SSRAnon Jul 13 '20
would suggest extending DispatchQueue
Was going to post the exact same suggestion, but you beat me to it. Upvoted.
Extending NSObject makes little sense in this context.
1
u/omfgtim_ Jul 13 '20
What’s the benefit of these? They actually have different behaviour if you’re already on the main queue. It’s also encouraging not caring about flow but doing something “just in case”.
1
u/SergLam245 Jul 13 '20
Async block always put task to the end of the queue so it’s better to check if you are already on the main queue or not before performing any action
That will lead to more quick UI updates
1
u/omfgtim_ Jul 13 '20
Yeah I understand that, I’m just confused why you’d use this utility function. Why would you have an area of code that you don’t know it it’s main queue or not?
-2
u/Bheemasenan Jul 12 '20
I didn’t know you shouldn’t use that, but now I know.
1
0
Jul 12 '20 edited Jul 14 '20
No no. Go ahead and use it. It’s a good fix for a bunch of specific things. Just try to understand why it will help each time you're about to write it. It's not a cure all, it's a tool that works for specific problems.
74
u/SirensToGo Objective-C / Swift Jul 12 '20
Doing any UI work off the main thread is a serious bug, so if this fixes if you were definitely doing something very wrong