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 Build a Weather App with Swift (Retired) Pulling Data From the Web Making a Network Call

Joseph Kandi
Joseph Kandi
2,640 Points

When requesting weather data, i get nil with the NSData

I have the following code

let apiKey = "bc9369ff33e690c4b3f1fc682fe0d03a"
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
let apiURL = NSURL(string: "37.8267,-122.423", relativeToURL: baseURL)!
let weatherData = NSData(contentsOfURL: apiURL, options: nil, error: nil)

the weatherData variable is nil, i am not sure why.

1 Answer

Joseph, you may have a expired code from forecast.io. Try the following:

  1. Sign in to forecast.io.

  2. Copy your account key and paste it into your apiKey constant.

This happened to me when building the weather app. After updating my account key, the data was successfully collected.

If you have any questions, feel free to ask!

Joseph Kandi
Joseph Kandi
2,640 Points

I have changed the code to this

        private let apiKey = "API_KEY"
        let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)")
        let forecastURL = NSURL(string: "\(baseURL!)/-33.915538,18.6560594")!

        let weatherData = NSData(contentsOfURL: forecastURL, options: nil, error: nil)
        let dictionaryData = NSJSONSerialization.JSONObjectWithData(weatherData!, options: nil, error: nil) as NSDictionary
        println(dictionaryData)

and it works. I think the issue was with the NSURL with the argument relativeToURL. It seems it wasnt constructing the right url