0

我最近一直在开发一个简单的 iOS 应用程序,它使用 NSURLSessionDownloadTask 从 Web 服务器下载图像。下载任务完美执行,但处理接收到的图像有点奇怪。尽管会话没有返回任何错误并且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.")
    }

}
4

0 回答 0