2016-11-15 3 views
0

날씨 API를 작성 중입니다. 다음 코드에서 오류가 :날씨 앱 : "선택 값을 언 래핑하는 동안 예기치 않게 nil이 발견되었습니다"swift3

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() 
}} 

받기 오류이 줄 :

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

오류 :

unexpectedly found nil while unwrapping an Optional value

사람이 이것에 대한 해결책이 무엇인지 알 수 있습니까?

+0

좋아해요을 풀기 그것은 잘 작동된다. '{ "coord": { "lon": 72.83, "lat": 21.17}, "weather": [{ "id": 800, "main": "clear", "description": "clear sky" { "temp": 302.713, "pressure": 1024.57, "humidity": 80, "temp_min": 302.713, "temp_max" "아이콘": "01d"}] : 302.713, "sea_level": 1024.73, "grnd_level": 1024.57}, "바람": { "속도": 5.26, "deg": 2.50101}, "구름": { "all": 0}, "dt" 1479205477, "sys": { "메시지": 0.0026, "country": "IN", "sunrise": 1479172774, "sunset": 1479212817}, "id": 1255364, "name": "Surat", "cod ": 200}' @vadian –

+0

App Transport Security가 안전하지 않은 http URL 사용을 금지한다고 생각됩니다. –

+0

P 목록에 추가했지만 같은 오류가 표시됩니다 @MattGibson –

답변

-1

귀하의 강제

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

대신이

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

} 
+0

@harsha –

0

사용자 내가 크롬에서 실행 한이

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)") 
       } 
      } 
     } 
+0

응용 프로그램을 성공적으로 실행 중이지만 아무런 데이터도 표시하지 않아서 동일한 오류가 표시되지 않았습니다. –

관련 문제