gpt4 book ai didi

ios - 如何在苹果 map 上加载JSON数据以放置标记IOS

转载 作者:行者123 更新时间:2023-12-01 19:04:09 25 4
gpt4 key购买 nike

嗨,我有一个服务器 json 格式的文件,其中包含几个 map 点:

["VALUE","proyect",[{"id":"1","name":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},morepoints..]]

我想在我的 ios 应用程序中将这些点作为标记放在我的 map 上。
我已经查看了几页和这里,但我没有找到任何东西,而且我尝试过的方法不起作用。

请问有什么帮助吗?

最佳答案

首先,您首先解析您的 JSON:

NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSAssert(array, @"%s: JSONObjectWithData error: %@", __FUNCTION__, error);

其次,您可以从该顶级数组中获取位置数组,为该数组中的每个位置字典创建注释,并将其添加到您的 map 中:
// the array of locations is the third object in the top-level array

NSArray *locations = array[2];

// now iterate through this array of locations

for (NSDictionary *location in locations)
{
// grab the latitude and longitude strings

NSString *latitudeString = location[@"lat"];
NSAssert(latitudeString, @"No latitude");
NSString *longitudeString = location[@"lng"];
NSAssert(longitudeString, @"No longitude");

// create the annotation and add it to the map

MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = CLLocationCoordinate2DMake([latitudeString doubleValue], [longitudeString doubleValue]);
annotation.title = location[@"name"];
annotation.subtitle = location[@"address"];
[self.mapView addAnnotation:annotation];
}

话虽如此,我必须说我不关心 JSON 格式:
["VALUE","proyect",[{"id":"1","name":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},morepoints..]]

对于我们来说,必须猜测这个数组中的第一个、第二个和第三个对象是什么,这是一个值得怀疑的设计。我们不应该神秘地捕获 array[2]获取位置数组。

数组应该用于等效项目的列表(例如,位置数组非常有意义)。但是这个顶级数组有点可疑,具有三种语义上非常不同的值类型,JSON 中没有任何内容可以指示这三个项是什么。

如果您坚持使用这种 JSON 格式,那么,很好,上面的代码应该可以完成这项工作。但希望您可以将此处的顶级结构更改为字典,而不是数组,您可以在其中使用键名来标识此顶级字典中的各种项目,例如:
{"id" : "VALUE", "project" : "proyect", "locations" : [{"id":"1","name":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},morepoints..]}

我不知道前两个值应该是什么,所以我只是称它们为 idproject ,但您显然应该使用真正反射(reflect)前两个值的名称。但关键概念是使用字典,您可以在其中按名称引用位置数组。例如,如果 JSON 像我在这里建议的那样更改,则解析它的代码将变为:
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSAssert(dictionary, @"%s: JSONObjectWithData error: %@", __FUNCTION__, error);

NSArray *locations = dictionary[@"locations"];

此外,作为一种风格观察,许多人通常会将纬度和经度值表示为数字(不带引号),而 NSJSONSerialization会将它们解析为 NSNumber对象而不是 NSString对象。但这取决于你。

关于ios - 如何在苹果 map 上加载JSON数据以放置标记IOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20923820/

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