简体   繁体   中英

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


}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM