skip to Main Content

Im updating an old app made with swift.
It was before the Storyborad and before SwiftUI.
The code is old I used to use .xib files and load them like this:

func loadNewScreen() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            let newScreen = NewScreen()
            newScreen.view.frame = self.view.bounds. //<- This is the line with the warning
            self.addChild(newScreen)

            UIView.transition(with: self.view, duration: 0.3, options: [.transitionCrossDissolve], animations: {
                self.view.addSubview(newScreen.view)
            }, completion: nil)
            
            newScreen.didMove(toParent: self)
        }
    }

Now I’m receiving a purple warning:

Performing I/O on the main thread can cause hangs. This is known to
cause hangs for your users.

I don’t use this kind of code anymore. Does anyone know what is the problem or how I should be loading the Views? Thanks

2

Answers


  1. Pull out this code block from DispatchQueue main and use the remaining code as it is for UI view transitions and animations.

    func loadNewScreen() {
                let newScreen = NewScreen()
                newScreen.view.frame = self.view.bounds
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                self.addChild(newScreen)
                UIView.transition(with: self.view, duration: 0.3, options: [.transitionCrossDissolve], animations: {
                    self.view.addSubview(newScreen.view)
                }, completion: nil)
                
                newScreen.didMove(toParent: self)
            }
        }
    
    Login or Signup to reply.
  2. I suspect the compiler is doing a fairly naive "he’s running code on the main thread, if that code does something time-consuming it could stall the main thread" analysis. I don’t see any "I/O" in your code, unless you’re crunching a bunch of data in your NewScreen() initializer.

    You can safely ignore that warning, or refactor as @SumitKumar suggests in their answer if that removes the warning.

    If you want to be sure, capture the Date at the beginning of your function and at the end use Date.timeIntervalSince(start) to figure out the amount of time elapsed. If it’s less than 1/60th of a second or so you can safely ignore the warning. (and I’m willing to bet the elapsed time will be a few MICROseconds.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search