更新UI Dispatch_Async后台下载Swift

时间:2015-07-30 18:58:36

标签: ios swift user-interface dispatch-async background-thread

我正在处理文件夹/文件应用程序,用户可以将文件下载到本地磁盘。每当用户下载文件时,我想显示一个显示进度的下载栏。

为此,我创建了一个允许我的下载类和我的视图控制器进行通信的协议:

协定:

protocol DownloadResponder : class {
    func downloadFinished()
    func downloadProgress(current:Int64, total:Int64)
}

下载课程

class fileDownloader: NSObject, NSURLSessionDelegate, NSURLSessionDownloadDelegate {

    //responder
    var responder : MyAwesomeDownloadResponder?

    init(responder : MyAwesomeDownloadResponder) {
        self.responder = responder
    }

    ...

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

        println("downloaded \(100*totalBytesWritten/totalBytesExpectedToWrite)")
        responder?.downloadProgress(totalBytesWritten, total: totalBytesExpectedToWrite)

    }

...

}

然后在我的视图控制器中,我有下载按钮,触发downloadProgress功能:

func downloadProgress(current:Int64, total:Int64) {
        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
        dispatch_async(dispatch_get_global_queue(priority, 0)) {
            // do some task
            var currentProgress = 100 * current / total
            dispatch_async(dispatch_get_main_queue()) {
                // update some UI
                self.downloadLbl.text = "Downloaded \(currentProgress)%"
                //set progress bar
                self.progressBar.setProgress(Float(currentProgress), animated: true)
            }
        }

    }

虽然控制台中的打印信息始终有效,但更新UI并不是很稳定。为了解决这个问题,我使用了dispatch_async方法来推送主线程上的UI更改。但是,虽然它始终在第一次工作,弹回到上一个视图控制器并再次返回,再次执行下载不会触发UI更新。进度条progressBar.setProgress不执行任何操作,我的标签downloadLbl.text不会自行更新。

有没有人知道如何解决这个问题? 如果我的问题缺乏信息,请告诉我,我会尝试添加现有信息。谢谢!

1 个答案:

答案 0 :(得分:4)

由于我没有收到/找到我的问题的任何解决方案,我回到更高级别并改变了我的类之间的通信方式,以根据后台下载线程进展来处理ui更改。

我没有使用协议,而是去了通知,它解决了我的问题。

在下载类中:

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

        println("downloaded \(100*totalBytesWritten/totalBytesExpectedToWrite)")

        //NOTIFICATION
        // notify download progress!
        var fileInfo = [NSObject:AnyObject]()
        fileInfo["fileId"] = fileDownloader.storageInfo[downloadTask.taskIdentifier]!["id"] as! Int!
        fileInfo["fileCurrent"] = Float(totalBytesWritten)
        fileInfo["fileTotal"] = Float(totalBytesExpectedToWrite)

        let defaultCenter = NSNotificationCenter.defaultCenter()
        defaultCenter.postNotificationName("DownloadProgressNotification",
            object: nil,
            userInfo: fileInfo)

    }

在视图控制器中:

override func viewDidLoad() {
        super.viewDidLoad()

        // ready for receiving notification
        let defaultCenter = NSNotificationCenter.defaultCenter()
        defaultCenter.addObserver(self,
            selector: "handleCompleteDownload:",
            name: "DownloadProgressNotification",
            object: nil)
    }

func handleCompleteDownload(notification: NSNotification) {
        let tmp : [NSObject : AnyObject] = notification.userInfo!

        // if notification received, change label value
        var id = tmp["fileId"] as! Int!
        var current = tmp["fileCurrent"] as! Float!
        var total = tmp["fileTotal"] as! Float!
        var floatCounter = 100 * current / total
        var progressCounter = String(format: "%.f", floatCounter)

        if(id == self.fileId){
            let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
                    dispatch_async(dispatch_get_global_queue(priority, 0)) {
                        // do some task
                        dispatch_async(dispatch_get_main_queue()) {
                            // update some UI
                            self.downloadLbl.text = "Downloaded \(progressCounter)%"
                            self.progressBar.setProgress((progressCounter as NSString).floatValue, animated: true)
                        }
                    }
        }
    }
希望这会有所帮助!