2016-11-15 30 views
0

我正在处理天气API。收到错误在下面的代码:天气应用程序:“意外地发现零,同时解开一个可选值”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

我已经在Chrome上运行它,它工作正常。 '{“coord”:{“lon”:72.83,“lat”:21.17},“weather”:[{“id”:800,“main”:“Clear”,“description”:“clear sky” “图标”: “01D”}], “基”: “站”, “主”:{ “温度”:302.713, “压力”:1024.57, “湿度”:80, “temp_min”:302.713, “temp_max” :302.713, “sea_level”:1024.73, “grnd_level”:1024.57}, “风”:{ “速度”:5.26, “DEG”:2.50101}, “云”:{ “所有”:0}, “DT”: 1479205477, “SYS”:{ “消息”:0.0026, “国”: “IN”, “日出”:1479172774, “夕阳”:1479212817}, “ID”:1255364, “名”: “苏拉特”,“鳕鱼“: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

没有差异显示相同的错误@哈沙 –

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

成功运行应用程序,但没有显示任何数据。 –

相关问题