Swift 中的运行时错误...NSData 为 Nill(不应该如此)

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

我在 Swift 中遇到运行时错误...下面有一个非常简单的程序。当那里应该有数据时,我得到了 data = nil。在这里挠头...

具体错误是"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)!


}

您不需要 fileURLWithPath: - 那是为了访问本地文件系统上的文件。你只需要 NSURL(string:) -

这在操场上对我有用 -

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