I've recently been working on a simple iOS application that uses a NSURLSessionDownloadTask to download an image from a web server. The download task executes perfectly, but dealing with the received image has proved to be a little odd. It seems as though the image is nil, although the session didn't return any errors and the URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
delegate method is called. The app then crashes giving the typical 'fatal error: found nil when unwrapping an optional value'
on the line var image: UIImage = UIImage(data: NSData(contentsOfURL: location)!)!
. Any ideas?
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.")
}
}