在 While 循环中更新标签 Swift

Update Label In While Loop Swift

如果我错了请纠正我,但是当我尝试在 while 循环中更新我的标签时它不会更新它。是 while 循环运行得太快导致标签无法在该时间内更新的原因,因此它会取消标签更新吗?

我需要解决这个问题吗?我需要能够立即更新标签吗?

func Download(complete: (canMoveOn: Bool) -> Void) {
    isDownload = true

    if (connected!) {
        Reset()

        let data = NSData(contentsOfFile: path!)!
        let buffer = (UnsafeMutablePointer<UInt8>(data.bytes))

        var leftOverSize = data.length
        let bytesFile = data.length
        var totalBytesRead = 0
        var bytesRead = 0

        let stream = CFReadStreamCreateWithFTPURL(nil, downloadURL!).takeUnretainedValue()
        let status = CFReadStreamOpen(stream)

        if (status == true) {
            while (totalBytesRead < bytesFile) {
                bytesRead = CFReadStreamRead(stream, buffer, leftOverSize)

                if (bytesRead > 0) {
                    totalBytesRead += bytesRead

                    if (bytesRead < bytesFile) {
                        leftOverSize = bytesFile - totalBytesRead
                    } else {
                        leftOverSize = 0
                    }
                } else {
                    break
                }

                //-------------Not Updating Label
                downloadLabel.attributedText = NSAttributedString(string: "\(totalBytesSent)", attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 20)!, NSForegroundColorAttributeName: UIColor.darkTextColor()])

                Calculate(bytesRead, totalBytesSent: totalBytesRead, totalBytesExpectedToSend: bytesFile)
            }

            CFReadStreamClose(stream)

            complete(canMoveOn: true)
        } else {
            Error()

            downloadLabel.attributedText = NSAttributedString(string: "- -", attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 20)!, NSForegroundColorAttributeName: UIColor.darkTextColor()])

            complete(canMoveOn: false)
        }
    }
}

尝试下面的代码,这一定会有效。

 while (currentSize < fileSize) {

        dispatch_sync(dispatch_get_main_queue(), { () -> Void in
            downloadLabel.attributedText = NSAttributedString(string: "\(currentSize) kbps", attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 20)!, NSForegroundColorAttributeName: UIColor.darkTextColor()])
            });

    }

只需将 UI 更新代码粘贴到主线程,如上所示。 原因:您无法从后台线程更新 UI。