显示图片从网址下载的速度与swift的载入百分比 [英] Show loading percentage of image download from url with swift

查看:115
本文介绍了显示图片从网址下载的速度与swift的载入百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个这样的url图像下载

So I have an image downloading from a url like so

        let request = NSMutableURLRequest(URL: NSURL(string: "\(self.ip)")!)
        request.HTTPMethod = "POST"
        let postString = "userID=\(userID)"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

        let task = session.dataTaskWithRequest(request) {
            data, response, error in
                   .........
        }

,我的委托函数看起来像

and my delegate functions look like

func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {

    let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
    let progressPercent = Int(uploadProgress*100)
    print(progressPercent)
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
    let downloadProgress:Float = Float(downloadTask.countOfBytesReceived) / Float(downloadTask.countOfBytesExpectedToReceive)
    print(downloadProgress)
}

上传进度对于不同的功能很好,但是当下载图像时,第二个URLSession功能不叫我做错了什么?

The upload progress works just fine for a different function, but when downloading an image, the second URLSession function does not get called. What am I doing wrong?

推荐答案

NSURLSession 有5种类型的代理: NSURLSessionDelegate NSURLSessionTaskDelegate NSURLSessionDataDelegate NSURLSessionDownloadDelegate NSURLSessionStreamDelegate 。您可以在文档中阅读相关内容。

NSURLSession has 5 types of delegate: NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate and NSURLSessionStreamDelegate. You can read about them in the documentation.

您需要关心的是 NSURLSessionDelegate NSURLSessionDownloadDelegate

class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDownloadDelegate {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var progressView: UIProgressView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func downloadImage(sender : AnyObject) {
        // A 20MB image from NASA
        let url = NSURL(string: "http://eoimages.gsfc.nasa.gov/images/imagerecords/78000/78314/VIIRS_3Feb2012_lrg.jpg")!

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)

        // Don't specify a completion handler here or the delegate won't be called
        let task = session.downloadTaskWithURL(url)     
        task.resume()
    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        print("Downloaded \(totalBytesWritten) / \(totalBytesExpectedToWrite) bytes ")

        dispatch_async(dispatch_get_main_queue()) {
            self.progressView.progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        }
    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        // The location is only temporary. You need to read it or copy it to your container before
        // exiting this function. UIImage(contentsOfFile: ) seems to load the image lazily. NSData
        // does it right away.
        if let data = NSData(contentsOfURL: location), image = UIImage(data: data) {
            dispatch_async(dispatch_get_main_queue()) {
                self.imageView.contentMode = .ScaleAspectFit
                self.imageView.clipsToBounds = true
                self.imageView.image = image
            }
        } else {
            fatalError("Cannot load the image")
        }

    }
}

这篇关于显示图片从网址下载的速度与swift的载入百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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