简体   繁体   English

取消下载NSData contentsOfUrl

[英]Cancel a download of NSData contentsOfUrl

I've got this class for downloading images. 我有这个课下载图像。 But I have a situation where I have multiple views that use this class to download images to them. 但是我有一个情况,我有多个使用此类的视图将图像下载到它们。 The views are dynamic and may disappear at anytime before the download has completed. 这些视图是动态的,可能在下载完成之前随时消失。

To prevent errors how would I modify this class to cancel the download should the view using it disappear? 为避免错误,如果使用该视图的视图消失了,我将如何修改此类以取消下载?

class ImageDownloader{
    var spinner = UIActivityIndicatorView()

    func fetchImage(imageView: UIImageView, url:NSURL, completed: (success: Bool) ->()) {
        self.spinner.frame = CGRectMake((imageView.frame.width-35)/2, (imageView.frame.height-35)/2, 35, 35)
        imageView.addSubview(self.spinner)
        self.spinner.startAnimating()
        let qos = Int(QOS_CLASS_USER_INITIATED.rawValue)
        dispatch_async(dispatch_get_global_queue(qos, 0)) { () -> Void in
            let imageData = NSData(contentsOfURL: url) // this blocks the thread it is on
            dispatch_async(dispatch_get_main_queue()) {
                self.spinner.removeFromSuperview()
                if imageData != nil {
                    imageView.image = UIImage(data: imageData!)
                    completed(success: true)
                }else{
                    completed(success: false)
                }
            }
        }
    }
}

After much research on this it seems NSURLSession is indeed the way to go for what I want to achieve. 经过大量研究之后,看来NSURLSession确实是我想要实现的目标。 I found it amazing that I struggled to find any decent tutorials or examples on this. 我很难找到与此有关的任何体面的教程或示例,这真是令人惊讶。 I ended up compiling from snippets of swift and objective-c code from here and there. 我最终从这里到那里的swift和Objective-c代码片段进行编译。

class imageDownloader:NSURLSession, NSURLSessionDelegate, NSURLSessionDownloadDelegate{
    var session:NSURLSession!
    var imageView:UIImageView!
    var task = NSURLSessionDownloadTask()
    var spinner = UIActivityIndicatorView()

    override init() {
        super.init()
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        self.session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    }

    func getImage(url:NSURL,imageView:UIImageView){
        self.imageView = imageView
        self.task = session.downloadTaskWithURL(url)
        self.spinner.frame = CGRectMake((imageView.frame.width-35)/2, (imageView.frame.height-35)/2, 35, 35)
        imageView.addSubview(self.spinner)
        self.spinner.startAnimating()
        self.task.resume()
    }


    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        let data = NSData(contentsOfURL: location)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.spinner.removeFromSuperview()
            self.imageView.image = UIImage(data: data! )
        }
    }

    func cancel(){
        self.task.cancel()
    }
}

As you can see there isn't much in the way of error handling. 如您所见,错误处理方式不多。 Can anyone suggest how to improve it to include this? 谁能建议如何改进它以包含此内容?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM