I'm developing an iOS app and at one view controller, I need to make a timer that repeats every 2 seconds and them update a stack view that is in the view controller. I made this code: viewDidLoad() Here starts my timer
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.information.numberOfLines = 20
configureView()
if #available(iOS 10.0, *) {
timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.reload), userInfo: nil, repeats: true)
} else {
self.information.isHidden = false
self.information.text = "Esta opción solamente es válida para dispositivos con iOS 10.0 o superior"
}
}
This is the configureView() method:
func configureView(){
if questionIndex != nil{
self.titulo.text = self.titulo.text! + " " + String(self.questionIndex!)
}
if self.statusCode! > 0{
if let numAns = self.numAnswers{
self.information.isHidden = true
for index in (0..<numAns){
let btn: UIButton = UIButton()
btn.backgroundColor = self.abcDary[self.abc[index % self.abc.count]]
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 21)
btn.setTitle(self.abc[index % self.abc.count], for: .normal)
btn.addTarget(self, action: #selector(self.answerSelected(sender:)), for: .touchUpInside)
self.stackRespuestas.addArrangedSubview(btn)
}
}
}
else{
self.information.isHidden = false
self.information.text = "Aún no puedes resolver esta pregunta"
}
}
and this is the reload method which is called by timer every 2 seconds:
@objc func reload(){
DispatchQueue.main.asyncAfter(deadline: .now()){
self.getStatus()
}
DispatchQueue.main.asyncAfter(deadline: .now()+1){
if self.information.isHidden == true && self.statusCode == 0{
for view in self.stackRespuestas.subviews{
if view is UIButton{
view.removeFromSuperview()
}
}
self.information.isHidden = false
self.information.text = "Aún no puedes contestar a esta pregunta"
}
else if self.information.isHidden == false && self.statusCode! > 0{
self.information.isHidden = true
self.configureView()
}
}
}
and this is the error:
Thread 2: "Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread."
Can anyone help me with this please?