Ios 如何将文件下载链接到进度视图

Ios 如何将文件下载链接到进度视图,ios,iphone,xcode,swift,uiprogressview,Ios,Iphone,Xcode,Swift,Uiprogressview,我下面的按钮代码从URL下载一个文件,我需要将其与进度视图链接以显示下载进度 @IBAction func btnStream(sender: UIButton) { // First you need to create your audio url if let audioUrl = NSURL(string: "http://website.com/file.mp3") { // then lets create your document fold

我下面的按钮代码从URL下载一个文件,我需要将其与进度视图链接以显示下载进度

@IBAction func btnStream(sender: UIButton) {

    //  First you need to create your audio url

    if let audioUrl = NSURL(string: "http://website.com/file.mp3") {

        // then lets create your document folder url
        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL

        // lets create your destination file url
        let destinationUrl = documentsUrl.URLByAppendingPathComponent(audioUrl.lastPathComponent!)
        println(destinationUrl)
        // to check if it exists before downloading it
        if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
            println("The file already exists at path")

            // if the file doesn't exist
        } else {

            //  just download the data from your url
            if let myAudioDataFromUrl = NSData(contentsOfURL: audioUrl){
                // after downloading your data you need to save it to your destination url
                if myAudioDataFromUrl.writeToURL(destinationUrl, atomically: true) {
                    println("file saved")
                } else {
                    println("error saving file")
                }
            }
        }
    }

}

如何将下载进度与Swift中的进度视图链接?

检查。它在Objective-C中,但很容易转换为Swift

原则是在VC上实现一些
NSURLConnectionDataDelegate
函数:

  • 连接:didReceiveResponse->您可以检索将下载的文件的大小,并估计下载百分比
  • 连接:didReceiveData->这是刷新功能,在下载过程中会被多次调用。您可以将不完整NSData对象的大小与文件的大小进行比较
  • connectiondFinishLoading->下载过程结束时调用此方法

希望对您有所帮助,如果您在将Obj-C转换为Swift时遇到一些问题,请不要犹豫发表评论。

以下是一个完整的工作示例:

import UIKit

class ViewController: UIViewController, NSURLSessionDownloadDelegate {


    @IBOutlet weak var progressBar: UIProgressView!
    @IBOutlet weak var progressCount: UILabel!

    var task : NSURLSessionTask!

    var percentageWritten:Float = 0.0
    var taskTotalBytesWritten = 0
    var taskTotalBytesExpectedToWrite = 0

    lazy var session : NSURLSession = {
        let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
        config.allowsCellularAccess = false
        let session = NSURLSession(configuration: config, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
        return session
        }()

    override func viewDidLoad() {
        progressBar.setProgress(0.0, animated: true)  //set progressBar to 0 at start
    }

    @IBAction func doElaborateHTTP (sender:AnyObject!) {

        progressCount.text = "0%"
        if self.task != nil {
            return
        }

        let s = "http://www.qdtricks.com/wp-content/uploads/2015/02/hd-wallpapers-1080p-for-mobile.png"
        let url = NSURL(string:s)!
        let req = NSMutableURLRequest(URL:url)
        let task = self.session.downloadTaskWithRequest(req)
        self.task = task
        task.resume()

    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
        println("downloaded \(100*writ/exp)")
        taskTotalBytesWritten = Int(writ)
        taskTotalBytesExpectedToWrite = Int(exp)
        percentageWritten = Float(taskTotalBytesWritten) / Float(taskTotalBytesExpectedToWrite)
        progressBar.progress = percentageWritten
        progressCount.text = String(format: "%.01f", percentageWritten*100) + "%"
    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        // unused in this example
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        println("completed: error: \(error)")
    }

    // this is the only required NSURLSessionDownloadDelegate method

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {

        let documentsDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL
        println("Finished downloading!")
        println(documentsDirectoryURL)
        var err:NSError?

        // Here you can move your downloaded file
        if NSFileManager().moveItemAtURL(location, toURL: documentsDirectoryURL.URLByAppendingPathComponent(downloadTask.response!.suggestedFilename!), error: &err) {
            println("File saved")
        } else {
            if let err = err {
                println("File not saved.\n\(err.description)")

            }
        }

    }

}
您可以使用
NSURLSessionDownloadDelegate
来实现此目的,用户下载数据时将调用其方法

这将向您显示进入
progressCount
标签的流程,
progressBar
将显示随着计数增加的流程。您可以根据需要对此进行修改


您可以从下载此示例。

Dharmesh Kheni,您的示例运行良好,但您的文件保存在哪里?您好@DharmeshKheni。如何为多个URL工作。我只是在尝试。我不能。若第二个URL正在进行,那个么在那个时候,若我启动第三个URL,则表示第二个URL已停止。我不知道如何同时运行所有url。我在试斯威夫特。请指导我。请随意打开另一个问题,如如何使用此方法处理多个URL…)@DharmeshKheni@DharmeshKheni如果你知道,请指导我。