0

I am working on weather API. getting error in following code:

fileprivate let openWeatherMapBaseURL = "http://api.openweathermap.org/data/2.5/weather"
fileprivate let openWeatherMapAPIKey = "b7ac98fd9b59acbe6078468d865bd908"

func getWeather(_ city: String) {

    // This is a pretty simple networking task, so the shared session will do.
    let session = URLSession.shared

    let weatherRequestURL = URL(string:"http://api.openweathermap.org/data/2.5/weather?q=\(city)&APPID=\(openWeatherMapAPIKey)")!

    let dataTask = session.dataTask(with: weatherRequestURL, completionHandler: {
        (data: Data?, response: URLResponse?, error: NSError?) in

        if let error = error{
        print("Error:\n\(error)")
        }

        else{
            print("Raw data:\n\(data!)\n")
            let dataString = String(data: data!, encoding: String.Encoding.utf8)
            print("Human-readable data:\n\(dataString!)")

        }
    } as! (Data?, URLResponse?, Error?) -> Void)
    dataTask.resume()
}}

Getting Error in this line:

let dataTask = session.dataTask(with: weatherRequestURL, completionHandler: {

error:

unexpectedly found nil while unwrapping an Optional value

do anyone know what is the solution for this?

Matt Gibson
  • 37,886
  • 9
  • 99
  • 128
maitree solanki
  • 135
  • 1
  • 13
  • i have run it in chrome and it is working fine. `{"coord":{"lon":72.83,"lat":21.17},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":302.713,"pressure":1024.57,"humidity":80,"temp_min":302.713,"temp_max":302.713,"sea_level":1024.73,"grnd_level":1024.57},"wind":{"speed":5.26,"deg":2.50101},"clouds":{"all":0},"dt":1479205477,"sys":{"message":0.0026,"country":"IN","sunrise":1479172774,"sunset":1479212817},"id":1255364,"name":"Surat","cod":200}` @vadian – maitree solanki Nov 15 '16 at 11:37
  • My guess would be that App Transport Security is prohibiting your use of the insecure http URL. – Matt Gibson Nov 15 '16 at 11:45
  • I added that in P list but showing same error @MattGibson – maitree solanki Nov 15 '16 at 12:02
  • Do you see anything in the debug console at the time of the error? – Matt Gibson Nov 15 '16 at 12:03
  • After Using Code which is given in answer it is running successfully but not showing any data. @MattGibson – maitree solanki Nov 15 '16 at 12:05
  • Seems to work for me if I don't do your odd force conversion of NSError to Error. – Matt Gibson Nov 15 '16 at 12:11
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/128162/discussion-between-maitree-solanki-and-matt-gibson). – maitree solanki Nov 15 '16 at 12:15
  • @maitreesolanki Try to encode your url string – Nirav D Nov 15 '16 at 12:15

2 Answers2

0

User this

let requestURL: NSURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(city)&APPID=\(openWeatherMapAPIKey)")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
        let session = URLSession.shared
        let task = session.dataTask(with: urlRequest as URLRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! HTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {
                do{
                    let jsonResponse  = try JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments) as? NSDictionary
                    print(jsonResponse)
                }catch {
                    print("Error with Json: \(error)")
                }
            }
        }
Yogendra Girase
  • 631
  • 3
  • 15
-1

Your forcibly unwrapping it

let weatherRequestURL = URL(string:"http://api.openweathermap.org/data/2.5/weather?q=\(city)&APPID=\(openWeatherMapAPIKey)")!

instead do like this

if let weatherRequestURL = URL(string:"http://api.openweathermap.org/data/2.5/weather?q=\(city)&APPID=\(openWeatherMapAPIKey)") {
// do your stuff

}
Rajat
  • 10,977
  • 3
  • 38
  • 55
Harsha
  • 59
  • 1