Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

ios - Objective C read JSON from URL into NSDictionary

So I am making an application that gets the users current location, then sends the Latitude and Longitude coordinates to this URL to see which desired stores are nearby. I am able to do everything I just mentioned, but am not sure how to read the content of the content of the webpage and use it to form a table view/ arrange it by shortest distance etc. I did some research and figured out this is JSON, and managed to parse the content from the URL into a NSDictionary with NSJSONSerialization. What I am not sure about is how to read the content of the NSDictionary containing the JSON syntax. I need keys like 'name', 'distance', 'formatted address', and to arrange my data in a UITableView by sorted 'distance' in ascending order.

Here is a screenshot of the JSON script i GET from the URL:JSON SCREENSHOT

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is how you can access an NSArray of the different venues:

  NSArray* locationsArray = jsonDictionary[@"response"][@"venues"];

From there you have access to all the location data. I would create a new model class for these locations with a CLLocation property to store the longitude and latitude as well as a distance property. Iterate through the array and instantiate the models while also calculating the distance from the device's current location:

NSMutableArray *locationObjectsArray;
for (NSDictionary *locationDict in locationsArray)
{
    Location *newLocation = [Location alloc] initWith...];
    newLocation.distance = [newLocation.coordinate distanceFromLocation:deviceLocation];
    [locationObjectsArray addObject:newLocation];
}

NSArray * results = [sortedLocations sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"distance"
                                                                              ascending:YES]]];

This should give you an array of locations sorted by distance from the device which you can now display in a table.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...