Coder221 Coder221 - 2 months ago 7
iOS Question

Delay in performSegue

I have a

bar button item
that segues to next view controller.I implemented
show segue
on the bar button item, it is having delay of 2 seconds for first time and then it is normal later.

I used
DispatchQueue
as follows but it still does the same

@IBAction func addPressed(_ sender: AnyObject) {
DispatchQueue.main.async(execute: {
self.performSegue(withIdentifier: "showDetail",sender: self)
})

}


This is what I have in second VC

override func viewDidLoad(){
super.viewDidLoad()

firstBtn.layer.borderWidth = 3
firstBtn.layer.borderColor = UIColor.white.cgColor

secondBtn.layer.borderWidth = 3
secondBtn.layer.borderColor = UIColor.white.cgColor


do{
let correctSoundUrl: URL = URL(fileURLWithPath: Bundle.main.path(forResource: "btnTap", ofType: "wav")!)
self.goalsTapPlayer = try AVAudioPlayer(contentsOf: correctSoundUrl)
self.goalsTapPlayer.prepareToPlay()
}
catch{}

}

Answer

DispatchQueue.main.async here does nothing as it's already executed on the main thread if it's called from a button press.

@IBAction func addPressed(_ sender: AnyObject) {
        self.performSegue(withIdentifier: "showDetail",sender: self)
}

Likely you have a problem in your prepareForSegue or viewDidLoad, viewWillAppear in the next controller.

If you have some heavy operation in those functions you should perhaps try to execute them on a background thread instead.

DispatchQueue.global(qos: .background).async {
    //Heavy operation
    //...
    DispatchQueue.main.async {
        //Potential update of UI
    }
}

in your case you can perhaps try to execute the audioplayerloading in the background

DispatchQueue.global(qos: .background).async {
    do{
        let correctSoundUrl: URL = URL(fileURLWithPath: Bundle.main.path(forResource: "btnTap", ofType: "wav")!)
        self.goalsTapPlayer = try AVAudioPlayer(contentsOf: correctSoundUrl)
        self.goalsTapPlayer.prepareToPlay()
    }
    catch{}
}
Comments