从swift中的dataTaskWithURL获得进度 [英] get progress from dataTaskWithURL in swift

查看:199
本文介绍了从swift中的dataTaskWithURL获得进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数据下载时,有没有办法在swift中从 dataTaskWithURL 取得进展?

Is there any way to get progress from dataTaskWithURL in swift while the data is downloading?

NSURLSession.sharedSession().dataTaskWithURL(...)

我需要在下载数据时显示进度条。

I need to show progress bar while the data is downloading.

推荐答案

您可以使用此代码显示带有代理功能的进度条的下载过程。

you can use this code for showing download process with progress bar with its delegate functions.

import UIKit

class ViewController: UIViewController,NSURLSessionDelegate,NSURLSessionDataDelegate{

    @IBOutlet weak var progress: UIProgressView!

    var buffer:NSMutableData = NSMutableData()
    var session:NSURLSession?
    var dataTask:NSURLSessionDataTask?
    let url = NSURL(string:"http://i.stack.imgur.com/b8zkg.png" )!
    var expectedContentLength = 0


    override func viewDidLoad() {
        super.viewDidLoad()
        progress.progress = 0.0
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let manqueue = NSOperationQueue.mainQueue()
        session = NSURLSession(configuration: configuration, delegate:self, delegateQueue: manqueue)
        dataTask = session?.dataTaskWithRequest(NSURLRequest(URL: url))
        dataTask?.resume()

        // Do any additional setup after loading the view, typically from a nib.
    }
    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {

        //here you can get full lenth of your content
        expectedContentLength = Int(response.expectedContentLength)
        println(expectedContentLength)
        completionHandler(NSURLSessionResponseDisposition.Allow)
    }
    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {


        buffer.appendData(data)

        let percentageDownloaded = Float(buffer.length) / Float(expectedContentLength)
        progress.progress =  percentageDownloaded
    }
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        //use buffer here.Download is done
        progress.progress = 1.0   // download 100% complete
    }
}

这篇关于从swift中的dataTaskWithURL获得进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆