ViewController 在等待调度信号量时作为弹出窗口

ViewController as Popup While Wait for Dispatch Semaphore

我在发出 URL JSON 请求时使用 Dispatch Semaphore 等待,这个等待可能需要一段时间。为了克服这种情况,我决定制作一个新视图,并在发出请求时将其显示为弹出窗口。为此,我使用了以下代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.showPopUp() 
    let semaphore = DispatchSemaphore(value: 0)

    self.api.requestMedicationsByReagent(method: 1, ean: "", hash: medHash!, gen: generic) { output in
        semaphore.signal()
        self.objects = output
    }
     // Thread will wait here until async task closure is complete
     let _ = semaphore.wait(timeout: DispatchTime.distantFuture)
}

showPopUp 的作用:

func showPopUp() {
    let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "loadingPopUp") as! PopUpViewController

    self.addChildViewController(popOverVC)
    popOverVC.view.frame = self.view.frame
    self.view.addSubview(popOverVC.view)
    popOverVC.didMove(toParentViewController: self)
}

问题在于,showPopUp 函数仅在请求已发出且弹出视图仅在屏幕上闪烁后才被调用。请求前如何调用?

问题是 wait 将阻塞主线程,直到信号量执行 signal,阻塞进程中的 UI(除其他外)。

我建议您完全消除该信号量。 (总的来说,这是一个非常糟糕的做法。)只需在启动异步请求之前显示弹出窗口并在完成处理程序中将其关闭(如果您的完成处理程序没有 [=17,请确保将其分派到主队列) =] 在主线程上)。