Getting a "This application is modifying the autolayout engine from a background thread" error?
Solution 1:
It needs to be placed inside a different thread that allows the UI to update as soon as execution of thread function completes:
Modern Swift:
DispatchQueue.main.async {
// Update UI
}
Older versions of Swift, pre Swift 3.
dispatch_async(dispatch_get_main_queue(){
// code here
})
Objective-C:
dispatch_async(dispatch_get_main_queue(), ^{
// code here
});
Solution 2:
You get similar error message while debugging with print statements without using 'dispatch_async' So when you get that error message, its time to use
Swift 4
DispatchQueue.main.async { //code }
Swift 3
DispatchQueue.main.async(){ //code }
Earlier Swift versions
dispatch_async(dispatch_get_main_queue()){ //code }
Solution 3:
The "this application is modifying the autolayout engine from a background thread" error is logged in the console long after the actual problem occured, so debugging this can be hard without using a breakpoint.
I used @markussvensson's answer to detect my problem and found it using this Symbolic Breakpoint (Debug > Breakpoints > Create Symbolic Breakpoint):
- Symbols:
[UIView layoutIfNeeded]
or[UIView updateConstraintsIfNeeded]
- Condition:
!(BOOL)[NSThread isMainThread]
Build and run the app on the emulator and replicate the steps that lead to the error message being thrown (the app will be slower than usual!). Xcode will then stop the app and mark the line of code (e.g. the call of a func) that's accessing the UI from a background thread.