Update Label In While Loop Swift

假装没事ソ 提交于 2019-12-30 14:45:44

问题


Correct me if I'm wrong, but when I try to update my label in a while loop it won't update it. Is the reason that the while loop runs too quickly for the label to update within that time so it'll cancel the label from updating?

I need a solution to this? I need to be able to update the label straight away?

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)
        }
    }
}

回答1:


Try Below Code, this will surely works.

 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()])
            });

    }

Just paste your UI update code to main thread as shown above. Reason : You can't update your UI from background thread.



来源:https://stackoverflow.com/questions/35126373/update-label-in-while-loop-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!