画面遷移時にMain Thread Checkerのエラーが出た時の対処法(Swift)


はじめに

画面遷移などをする際に下記のようなエラーが出た時の対処法を紹介します。

エラー内容
"Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread"
"Main Thread Checker: UI API called on a background thread"

対処法 (DispatchQueue.main)

DispatchQueue.main.sync {} もしくは DispatchQueue.main.async {} の中に対象のコードを入れる

同期処理の場合

DispatchQueue.main.sync {
  navigationController?.popViewController(animated: true)  ←ここに画面遷移などのコードを記載
}


非同期処理の場合

DispatchQueue.main.async {
  navigationController?.popViewController(animated: true)  ←ここに画面遷移などのコードを記載
}

原因

UIの更新はメインスレッドで行う必要があるため、DispatchQueue.mainに処理を追加しないといけないとのこと。
https://1000ch.net/posts/2016/dispatch-queue.html
https://developer.apple.com/documentation/dispatch/dispatchqueue