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

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