我正在开发一个应用程序,我从网上下载数据。 在这里我使用取消按钮取消下载进度,如果我在相同的视图控制器,如果我导航到新的视图控制器并返回到下载视图控制器进度视图不更新,但下载正在发生,这工作正常。
这是我用来下载数据的代码
func URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL){
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = NSFileManager()
let destinationURLForFile = NSURL(fileURLWithPath: documentDirectoryPath.stringByAppendingString( Variables.name ))
if fileManager.fileExistsAtPath(destinationURLForFile.path!){
print("File Already Exists")
} else {
do {
try fileManager.moveItemAtURL(location, toURL: destinationURLForFile)
print("File doesn't exists")
}catch{
print("An error occurred while moving file to destination url")
}
}
}
// 2
func URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten writ: Int64,
totalBytesExpectedToWrite exp: Int64){
//progressView.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
print("downloaded \(100*writ/exp)")
dispatch_async(dispatch_get_main_queue(), {
self.counter = Float(100*writ/exp)
return
})
}
func URLSession(session: NSURLSession,
task: NSURLSessionTask,
didCompleteWithError error: NSError?){
downloadTask = nil
// progressView.setProgress(0.0, animated: true)
if (error != nil) {
print(error?.description)
} else {
print("The task finished transferring data successfully")
}
}
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController{
return self
}