Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Harry Tennent
Harry Tennent
2,275 Points

NSData Error - Making a Network Call

I was working my way through the Weather app tutorial and came across an error where it stated that there was a:

"fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) "

Here is my code:

    import UIKit

    class ViewController: UIViewController {

    private let apiKey = "PRIVATEAPIKEY"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let baseURL = NSURL(string: "https://api.forecast.io/\(apiKey)/")
        let forecastURL = NSURL(string: "51.112124, -0.736092", relativeToURL: baseURL)

        let weatherData = NSData(
            contentsOfURL: forecastURL!,
            options: nil,
            error: nil
        )

        println(weatherData)


    }

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


    }

1 Answer

Pasan Premaratne
STAFF
Pasan Premaratne
Treehouse Teacher

Harry Tennent,

When defining the forecastURL and passing in the location coordinates as a string, it can't have a space between after the common and the second location point.

So "51.112124,-0.736092" instead of "51.112124, -0.736092".

Harry Tennent
Harry Tennent
2,275 Points

I did this and it now doesn't have an error but it instead prints "nil" to the console?

Pasan Premaratne
Pasan Premaratne
Treehouse Teacher

Could you link me to your entire project? Either via github or a zip file.

Pasan Premaratne
Pasan Premaratne
Treehouse Teacher

Harry Tennent

Your base url is incorrect. It should be "https://api.forecast.io/forecast/\(apiKey)/" and not "https://api.forecast.io/\(apiKey)/". You're missing the /forecast/ bit after forecast.io.

Harry Tennent
Harry Tennent
2,275 Points

Great, that works! Thanks!