SKY*_*ine 1 user-interface ios background-thread dispatch-async swift
我正在使用文件夹/文件应用程序,用户可以在其中将文件下载到本地磁盘。每当用户下载文件时,我都想显示一个显示进度的下载栏。
为此,我创建了一个协议,该协议允许我的下载类和视图控制器进行通信:
协议:
protocol DownloadResponder : class {
func downloadFinished()
func downloadProgress(current:Int64, total:Int64)
}
Run Code Online (Sandbox Code Playgroud)
下载类:
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)
}
...
}
Run Code Online (Sandbox Code Playgroud)
然后在我的视图控制器中,我有一个触发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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
尽管在控制台中始终打印信息,但更新UI并不是很稳定。为了解决这个问题,我使用了dispatch_async方法将UI更改推送到主线程上。但是,尽管它总是第一次工作,但弹出到先前的视图控制器然后再次返回,再次执行下载不会触发UI更新。进度栏progressBar.setProgress不执行任何操作,我的标签downloadLbl.text也不会自动更新。
有谁知道解决这个问题的方法吗?如果我的问题缺少信息,请告诉我,我将尝试加总现有信息。谢谢!
由于我没有收到/找到解决问题的任何方法,因此我回到了更高的层次,并更改了类之间进行通信的方式,以根据后台下载线程的进度来处理ui更改。
我没有使用协议,而是去了Notifications,它解决了我的问题。
在下载类中:
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)
}
Run Code Online (Sandbox Code Playgroud)
在视图控制器内部:
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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
希望对您有所帮助!
| 归档时间: |
|
| 查看次数: |
2511 次 |
| 最近记录: |