Swift中的运行时错误... NSData是Nil(当它不应该是#39; t)

时间:2015-02-22 01:59:24

标签: ios swift nsdata optional

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

特定错误是"致命错误:在展开可选值时意外发现nil"

//
//  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)!


}

1 个答案:

答案 0 :(得分:0)

您不希望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!)
    }
}