1

我一直在设计一个分析文本行的应用程序,我想使用 SVProgressHUD 来显示它的进度。

这是我的代码:

let total = text.count
for line in text{
    count = count + 1
    DispatchQueue.global(pos: .background).async{
        //Analyzing line
        DispatchQueue.main.async{
            SVProgressHUD.showProgress(count/total)
        }
    }
}

分析成功,HUD显示正常,当count到达时total,进程卡住,SVProgressHUD停止在max状态,程序停止。程序有什么问题?

我使用 Dispatchqueue 错了吗?我是否必须调用其他东西来释放后台进程或其他东西?

我试过交换//Analyzing lineand SVProgressHUD.show...,但还是不行。我最初在没有 dispatchqueue 的循环中使用 SVProgress,但是只有在分析(完整循环)完成后,进度 hud 才会移动,这是一个问题。

任何帮助,将不胜感激。

谢谢你。

4

2 回答 2

1

尝试使用此代码。它不使用循环,而是实现对用于处理字符串数据的函数的递归调用。

func processLines() {
    SVProgressHUD.showProgress(0)

    // sample data
    var text = Array("abcdefghijklmnop")
    var lines : [Line] = []
    let count : [Int] = Array(0..<text.count)
    count.forEach({ pos in lines.append(Line(char: text[pos])) })
    var currentIndex : Int = 0

    func processLine(at index: Int) {

        DispatchQueue.global(qos: .background).async{
            //Analyzing line
            let line = lines[index]
            print("Processing Line CHAR: \(line.char)")

            DispatchQueue.main.async{
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    guard currentIndex < lines.count-1 else {
                        SVProgressHUD.showProgress(1)
                        return
                    }
                    currentIndex += 1
                    startLineProces(at: currentIndex)
                }
            }
        }

    }

    func startLineProces(at index: Int) {
        processLine(at: index)
        SVProgressHUD.showProgress(Float(index) / Float(lines.count))
    }


    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        startLineProces(at: currentIndex)
    }
}

struct Line {
   var char: Character
   init(char: Character) {
     self.char = char
   }
}
于 2018-09-21T09:29:18.037 回答
1

使用以下字符串扩展名来分析您的字符串。它有一个完成块,它将返回进度以及完成状态。

extension String {
func analyseString(completion: @escaping (Bool, Float) -> ()) {
    let totalCountOfString = self.count
    for (index, _) in self.enumerated() {
        if index == totalCountOfString - 1 {
            completion(true, Float(index)/Float(totalCountOfString))
        } else {
            completion(false, Float(index)/Float(totalCountOfString))
        }
    }
  }
}

您可以调用上述方法来显示您的进度,如下所示(可能是单击按钮)。self.yourString是您需要分析的输入字符串。

@IBAction func clicked(_ sender: UIButton) {
    DispatchQueue.main.async {
        self.yourString.analyseString { (isCompleted, progress) in
            if isCompleted {
                SVProgressHUD.dismiss()
                print("Ending")
            } else {
                SVProgressHUD.showProgress(progress, status: "Analysing (\(progress)%)")
            }
        }
    }
}
于 2018-09-18T08:32:06.877 回答