iOS Build a Weather App Dark Sky API Client Cleaning Up The View Controller

Christian A. Castro
Christian A. Castro
18,830 Points

Error message, Nil Optional(Stormy.DarkSkyError.invalidUrl) Build a Weather APP! HELP PLEASE !??

Any idea why I'm unable to retrieve the information from the Darksky API.. Error message that prints on the console: Error message, Nil Optional(Stormy.DarkSkyError.invalidUrl)

This is my DarkAPIClient class:

import Foundation

class DarkSkyAPIClient
{
    fileprivate let darkSkyApiKey = "a43da7b64e8d9a6e918a4ef22e56f6a8"

    lazy var baseUrl: URL = {
        return URL(string: "https://api.darksky.net/forecast/\(self.darkSkyApiKey)/")!
    }()

    let downloader = JSONDownloader()

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

    private func getWeather(at coordinate: Coordinate, completionHandler completion: @escaping WeatherCompletionHandler)
    {

        guard let url = URL(string: coordinate.description, relativeTo: baseUrl) else
        {
            completion(nil, .invalidUrl)
            return
        }

        let request = URLRequest(url: url)

        let task = downloader.jsonTask(with: request) {json, error in

            guard let json = json else
            {
                //If is nil..
                completion(nil, error)
                return
            }
            guard let weather = Weather(json: json) else
            {
                completion(nil, .jsonParsingFailure)
                //Exit the current scope
                return
            }
            completion(weather, nil)
        }

        task.resume()
    }

    func getCurrentWeather(at coordinate: Coordinate, completionHandler completion: @escaping CurrentWeatherCompletionHandler)
{
//Calling
    getWeather(at: coordinate){weather, error in

        completion(weather?.currently, error)

        }
    }
}
Jhoan Arango
Jhoan Arango
Treehouse Moderator 12,851 Points

Hello,

Have you checked the URL that you are constructing ? it may be wrong

Christian A. Castro
Christian A. Castro
18,830 Points

Jhoan Arango Thank you for your quick response. I actually did!!! but I will double check again, I will keep you posted, blessing!

2 Answers

Hey not sure if you found a solution yet, however I was having the same problem and I think I found the cause. Check your coordinate file. I had a space between latitude and longitude making my url invaild.

extension Coordinate: CustomStringConvertible { var description: String { return"(latitude),(longitude)" }

Christian A. Castro
Christian A. Castro
18,830 Points

Joseph Devlin thank you for your feedback!! I actually was missing some extensions within the CurrentWeather swift file. Once I added that code and changed certain variables, it just started working!! Have a bless one!!