gpt4 book ai didi

json - 添加注释会导致在展开可选值时意外发现 nil

转载 作者:行者123 更新时间:2023-11-28 09:11:33 27 4
gpt4 key购买 nike

目前正在使用 json 和 mapkit,从 json 获取经度和纬度。使用数组存储 json 结果,而不是使用 for 循环从数组中获取经度和纬度,如下所示

dispatch_async(dispatch_get_main_queue(), { () -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var allContacts: AnyObject! = NSJSONSerialization.JSONObjectWithData(allContactsData!, options: NSJSONReadingOptions(0), error: nil)
self.dataArray = allContacts as [AnyObject]

for(self.i = 0; self.i < self.dataArray.count; self.i++){
println(self.dataArray[self.i])
var dict: NSDictionary = self.dataArray[self.i] as NSDictionary
self.crimeCat = dict["category"] as? String
self.crimeName = dict["name"] as? String
var crimeLat = dict["latitude"] as CLLocationDegrees //throws an error here
var crimeLong = dict["longitude"] as CLLocationDegrees
//println(self.crimeName)

var crimeLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(crimeLat,crimeLong)
var annotation = MKPointAnnotation()
annotation.coordinate = crimeLocation
annotation.title = self.crimeCat!
self.map.addAnnotation(annotation)
}
println(allContacts)

但是每当我运行应用程序时我得到

fatal error: unexpectedly found nil while unwrapping an Optional value

我添加了断点,细节似乎加载正确

以下是我尝试过的方法

self.crimeLat = dict["latitude"] as? CLLocationDegrees
self.crimeLong = dict["longitude"] as? CLLocationDegrees


var crimeLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(self.crimeLat,self.crimeLong) //when i try this method i get same error here

我知道返回的结果有纬度和经度,因为我已经测试过了。

任何建议我可能做错了什么?谢谢

最佳答案

正如 lchamp 所说,我提取 json 数据的方式不正确,返回了 json

location{
latitude = "somevalue"
longitude = "somevalue"
}

我修改了下面的代码

self.crimeLat = dict["latitude"] as? CLLocationDegrees
self.crimeLong = dict["longitude"] as? CLLocationDegrees

 self.crimeLat = ((dict["location"] as NSDictionary)["latitude"] as NSString).doubleValue
self.crimeLong = ((dict["location"] as NSDictionary)["longitude"] as NSString).doubleValue

现在已经解决了这个问题。

关于json - 添加注释会导致在展开可选值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29158021/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com