2016-02-05 72 views
-1

在使用alamofire https://maps.googleapis.com/maps/api/directions/json?origin=(self.startlat,self.startlng)&destination=(self.endlat,self.endlng错误意外地发现零而展开的可选值

我收到此错误所有的时间打电话:

'fatal error: unexpectedly found nil while unwrapping an Optional value'

我也试试这个

if let slat = startlat { 
    if let slng = self.startlng { 
     if let elat = self.endlat { 
      if let elng = self.endlng { 
       Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/directions/json?origin=\(slat,slng)&destination=\(elat,elng)" , encoding: .JSON) 
       .responseJSON { response in 
        let res = response.result.value! 
        self.estimatedDistance = (res["routes"]!![0]["legs"]!![0]["distance"]!!["value"] as! Int)/1000 
        self.estimatedTime = (res["routes"]!![0]["legs"]!![0]["duration"]!!["value"] as! Int)/60 
        print("\(self.estimatedDistance) - \(self.estimatedTime)") 

       } 
      } 
     } 
    } 
} 

,但我仍然会有同样的错误。

+0

'guard/else'是你的朋友;) –

+0

你还有几个强制解包。调试器光标指向哪一行? –

+0

保持力量展开从来不是一个好主意,如果你觉得懒得'如果let'或'guard let'那么考虑使用[Swifty JSON](https://github.com/SwiftyJSON/SwiftyJSON),它会帮助 – Tj3n

回答

0

从谷歌的API调用JSON结果:

{ 
    "geocoded_waypoints" : [ 
     { 
     "geocoder_status" : "ZERO_RESULTS" 
     }, 
     { 
     "geocoder_status" : "ZERO_RESULTS" 
     } 
    ], 
    "routes" : [], 
    "status" : "NOT_FOUND" 
} 

似乎您试图访问res["routes"][0]!!,但在这种情况下,(在你的链接)res["routes"] JSON元素是一个空数组。

+0

但是,此直接值链接“https://maps.googleapis.com/maps/api/directions/json?origin=28.6691565,2077.4537578&destination=28.4594965,2077.0266383”正在工作 – sasuke

+0

是链接完全正常工作,但在路由元素中,您是试图获得数组的第一个值,但数组是空的。在获取其中一个之前,你必须检查数组是否有值。 – Nerkyator

+0

“'\(self.startlat)'”自动添加“(”在字符串中如何避免? – sasuke

相关问题