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 Dark Sky API Client Cleaning Up The View Controller

Aditya Pandey
Aditya Pandey
7,210 Points

Getting the wrong url

I was trying to get the correct url but when I printed the description of the url I get this: 37.8267,-122.4233 -- https://api.darksky.net/forecast/f4bc0720ca89fed805f1ab941ebae16d/

I wrote this code:

lazy var baseUrl: URL = {

    return URL(string: "https://api.darksky.net/forecast/\(self.apiKey)/")!
}()


let downloader = JSONDownloader()

typealias CurrentWeatherCompletionHandler = (CurrentWeather?, DarkSkyError?) -> Void

func getCurrentWeather(at coordinate: Coordinate, completionHandler completion: @escaping CurrentWeatherCompletionHandler) {

    guard let url = URL(string: coordinate.description, relativeTo: baseUrl) else {

        completion(nil, .invalidUrl)
        return
    }

    let request = URLRequest(url: url)


    print(url.description)

I don't know what I did wrong. I appreciate any help.

3 Answers

Aditya Pandey
Aditya Pandey
7,210 Points

Where is the error? Please send the code.

Ingo Ngoyama
Ingo Ngoyama
4,882 Points

This is the code in the bottom console:

nil

Optional(Stormy.DarkSkyError.invalidUrl)

Ingo Ngoyama
Ingo Ngoyama
4,882 Points

I have traced it down to the DarkSkyAPI.swift so far below on the 32nd line where I make the URL with gaurd let url = URL which is inside the func getCurrentWeather:

import Foundation

class DarkSkyAPIClient { fileprivate let apiKey = "4bcc4b5d0feab3ff87823f5a2c6b7387" // store the API key (paste from VC) and call it ApiKey

// base url to interact with the DkSky api used to make each call when we need it in future
lazy var baseUrl: URL = {

    //paste "base" from VC.
    //let base = The Darksky connection URL but mmodified as below
    //chg "let base=" to  "return" and "darksky" to "self.apiKey"
    //now we have an optional Url but we force unwrap with !
    return URL(string: "https://api.darksky.net/forecast/\(self.apiKey)/")! // its cool to  crash with ! if url cant be created.
}()

let downloader = JSONDownloader() // hold on to an  instance of JSONDownloader()

typealias CurrentWeatherCompletionHandler = (CurrentWeather?, DarkSkyError?)-> Void

func getCurrentWeather(at coordinate: Coordinate, completionHandler completion: @escaping CurrentWeatherCompletionHandler) {


    guard let url = URL(string: coordinate.description, relativeTo: baseUrl) else {// make url
        completion(nil, .invalidUrl)// make this error in DarkSkyError file
        return
    }

    let request = URLRequest(url: url)//make a requestor to use to make requests with

    // ask JSONDownloader to make a request on our behalf
    let task = downloader.jsonTask(with: request) { json, error in

        // after we create the Current Weather instance and convert it to Json in the CurrentWeather file
        guard let json = json else{// unwrap the task
            completion(nil, error)
            return
        }// now we have a valid json object

        guard let currentWeatherJson = json["currently"] as? [String: AnyObject], let currentWeather = CurrentWeather(json: currentWeatherJson) else {
            completion(nil, .jsonParsingFailure)
            return
        }

        completion(currentWeather,nil)

        // now the taks is made and ready
    }

    task.resume() // this will actually start the task
}

}

guys the thanks for the help one thing though the app run but the temperature does change and the spinning wheel keeps spinning

andre figueiredo
andre figueiredo
5,881 Points

I got the same error . took me a while to figure out.

In my case it was a mere extra space at the "coordinate.description" in Coordinate.swift file:

extension Coordinate: CustomStringConvertible { var description : String { return "(latitude),(longitude)" // You should have no space in this string otherwise you gonna mess up the url. <--- }

Aditya Pandey
Aditya Pandey
7,210 Points

Ok I understood what was wrong.

Ingo Ngoyama
Ingo Ngoyama
4,882 Points

What was it? i have the same Problem.

hey could you have me i have run into a little problem my console says fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)