NSURLSessionDownloadDelegate使用UIImage生成错误

时间:2015-02-08 07:52:47

标签: ios swift nsurlsessiondownloadtask

我最近一直在研究一个简单的iOS应用程序,它使用NSURLSessionDownloadTask从Web服务器下载图像。下载任务完美地执行,但处理接收到的图像已被证明有点奇怪。看起来好像图像是nil,虽然会话没有返回任何错误,并且调用了URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)委托方法。该应用随后崩溃,在'fatal error: found nil when unwrapping an optional value'行上显示典型的var image: UIImage = UIImage(data: NSData(contentsOfURL: location)!)!。有什么想法吗?

import UIKit

class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDownloadDelegate {

    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: .Fade)

        let filePath: NSString = NSString(string: "https://www.codekaufman.com/screen.png")

        let session = NSURLSession(configuration: .defaultSessionConfiguration(), delegate: self, delegateQueue: nil)
        let downloadTask = session.downloadTaskWithURL(NSURL(string: filePath)!)

        downloadTask.resume()
        activityIndicator.startAnimating()
    }

    override func viewWillDisappear(animated: Bool) {
        UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: .Fade)
    }

    // MARK: Download Delegate Funcions

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {

    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        println("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        dispatch_async(dispatch_get_main_queue(), {
            self.activityIndicator.stopAnimating()
            if UIImage(data: NSData(contentsOfURL: location)!) != nil {
                var image: UIImage = UIImage(data: NSData(contentsOfURL: location)!)!
                self.imageView.image = image
            } else {
                println("Image was nil.")
            }
        })
        println("Finished download task.")
    }

}

0 个答案:

没有答案