Search code examples
iosswiftnsdataoption-type

Runtime error in Swift...NSData is Nill (when it shouldn't be)


I am getting a runtime error in Swift...I have a very simple program below. I am getting data = nil when there should be data there. Scratching my head here...

The specific error is "fatal error: unexpectedly found nil while unwrapping an Optional value"

//
//  ViewController.swift
//  TestingImageLoad
//
//  Created by Daniel Riaz on 2/21/15.
//  Copyright (c) 2015 Daniel Riaz. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var testImage: UIImageView!

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

        // Do any additional setup after loading the view, typically from a nib.
    }

    func loadImage() {
        var url: String = "http://imgur.com/jn4z6wpl.jpeg"
        let testURL: NSURL = NSURL(fileURLWithPath: url)!
        let data: NSData = NSData(contentsOfURL: testURL)!
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    //URL that works to use http://imgur.com/jn4z6wpl.jpeg

//    var postURL: NSURL = NSURL(string: self.detailPost!.url)!
//    var data: NSData = NSData(contentsOfURL: postURL)!
//    var imageToShare = UIImage(data: data)!


}

Solution

  • You don't want fileURLWithPath: - that is for access to files on the local file system. You just want NSURL(string:) -

    This worked for me in a Playground -

    func loadImage() {
        var url: String = "http://imgur.com/jn4z6wpl.jpeg"
        let testURL = NSURL(string:url)
        if (testURL != nil) {
           let data =  NSData(contentsOfURL: testURL!)
        }
    }