Swift 从闭包内部添加 VC 无效

Swift adding VC from inside a closure not working

所以我试图在用户点击按钮时显示加载视图。下面是函数

    /// Handles the shutter button tapped
    @objc func shutterTapped() {
        let parent = self.parent as! CameraActionViewController

        if parent.timerEngine.currentTime != 0 { parent.timerEngine.presentTimerDisplay() }
// This acts as a timer for the shutter to fire. (like a timer function for a camera)
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(parent.timerEngine.currentTime)) {

            parent.cameraManager.capturePictureWithCompletion({ result in
                switch result {
                case .failure:
                    AlertHelper.shared.presentDefault(title: "Error", message: "Looks like there was an error capturing the image.", to: self)

                case .success(let content):
                    let loadingVC = LoadingViewController()
                    parent.parent!.addVC(loadingVC)
                    print("processing...")

                    if let image = content.asImage {
                        guard let editedImage = FilterEngine.shared.process(originalImage: image) else {
                            TapticHelper.shared.errorTaptic()
                            return
                        }

                        guard let data = editedImage.jpegData(compressionQuality: 1.0) else {
                            TapticHelper.shared.errorTaptic()
                            return
                        }

                        DataEngine.shared.save(imageData: data)
                        print("Success")
                        TapticHelper.shared.successTaptic()
                        loadingVC.removeVC()
                    }
                }
            })
        }
    }

当相机成功捕获图像并开始使用用户选择的所有滤镜进行编辑时,我想显示加载视图。因为这是一项繁重的任务,会冻结UI一秒钟。

let loadingVC = LoadingViewController()
parent.parent!.addVC(loadingVC)
...
loadingVC.removeVC()

添加方法在这里:

    func addVC(_ child: UIViewController) {
        addChild(child)
        view.addSubview(child.view)
        child.didMove(toParent: self)
    }

    func removeVC() {
        guard parent != nil else { return }

        willMove(toParent: nil)
        view.removeFromSuperview()
        removeFromParent()
    }

但由于某种原因,它根本没有显示视图。然后我发现它以某种方式在 DataEngine.shared.save(imageData: data) 行之后执行(添加到 VC)。因此,由于它是同时添加和删除的,所以它什么也没有显示。

有什么帮助吗?

您需要将所有 UI 相关任务分派到主队列。尝试:

DispatchQueue.main.async {
    parent.parent!.addVC(loadingVC)
}

并且:

DispatchQueue.main.async {
    loadingVC.removeVC()
}

或者在后台任务完成后立即将所有内容放入主队列:

parent.cameraManager.capturePictureWithCompletion({ result in
    DispatchQueue.main.async {
        //...
    }
}