NSProgressIndicator无法在回调函数内部工作

时间:2017-01-26 16:26:24

标签: swift macos cocoa nsprogressindicator

我有一个NSProgressIndicator(进度条),在这样的委托方法中似乎可以正常工作:

func restClient(client: DBRestClient!, uploadProgress progress: CGFloat, forFile destPath: String!, from srcPath: String!) {
        if progress == 1.0 {
            progressBar.hidden = true
            generalAlert("Uploaded", text: "Your File has been saved to your computer and uploaded under: \(destPath)")
        } else {
            progressBar.hidden = false
            print(progress) // e.g 0.010213
            progressBar.doubleValue = Double(progress)*100
        }
    }

但是,当放在带回调函数内部时,我似乎无法以任何方式修改它(既不接受我的isHidden = false调用,也不接受doubleValue更新)。

CloudConvert.convert([
            "inputformat": "gif",
            "outputformat" : "mov",
            "input" : "upload",
            "file": name],

            progressHandler: { (step, percent, message) -> Void in
                print(percentage!) //e.g 10.31451. Called every second
                self.progressBar.hidden = false //Doesn't Work
                self.progressBar.doubleValue = Double(percentage!) //Doesn't Work
            },
            completionHandler: { (path, error) -> Void in
                if(error != nil) {
                    self.progressBar.hidden = true
                    self.generalAlert("ERROR", text: "Your file could not be uploaded")
                } else {
                    self.progressBar.hidden = true
                    self.generalAlert("MOV Uploaded", text: "Your MOV has been saved to your computer and uploaded")
                }
        })

任何人都可以知道为什么会这样吗?

2 个答案:

答案 0 :(得分:1)

您的完成处理程序将在后台线程中运行所有内容,您需要在主线程上进行UI调用。

将调度中的进度条调用汇总到主队列中,如下所示

    DispatchQueue.main.async(execute: {
        self.progressBar.hidden = false //Should now Work
        self.progressBar.doubleValue = Double(percentage!) //Should now Work
    })

答案 1 :(得分:1)

尝试将您的UI代码放在DispatchQueue.main.async块中。 UI操作关闭主线程会出现延迟。