Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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!