我一直在设计一个分析文本行的应用程序,我想使用 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 line
和 SVProgressHUD.show...
,但它仍然不起作用。我最初在没有调度队列的循环中使用 SVProgress,但随后进度 HUD 仅在分析(完整循环)完成后才移动,这是一个问题。
如有任何帮助,我们将不胜感激。
谢谢。
最佳答案
尝试使用此代码。它不使用循环,而是实现对用于处理字符串数据的函数的递归调用。
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
}
}
关于swift - swift 中的 Dispatchqueue 和 SVProgressHUD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52380832/