iOS下解析Geo数据提取经纬度并入字典数组技术求助
Got it, let's break this down step by step. You've successfully fetched and started parsing the JSON data—now we just need to extract the longitude and latitude from that A_Geo string format and add those values to your Article objects.
1. First, write a helper function to parse the Geo string
The A_Geo value is in the format "MULTIPOINT ((lng lat))", so we need to strip out the extra characters and split the remaining string into two numerical values:
func parseGeoCoordinates(from geoString: String) -> (longitude: Double?, latitude: Double?) { // Clean up the string by removing the "MULTIPOINT (" and trailing "))" let cleaned = geoString.replacingOccurrences(of: "MULTIPOINT ((", with: "") .replacingOccurrences(of: "))", with: "") .trimmingCharacters(in: .whitespaces) // Split the cleaned string into two parts using whitespace as the separator let coords = cleaned.components(separatedBy: .whitespaces) guard coords.count == 2, let lng = Double(coords[0]), let lat = Double(coords[1]) else { // Return nil if parsing fails (invalid format or non-numeric values) return (nil, nil) } return (lng, lat) }
2. Update your JSON parsing logic
In the loop where you process each articleDict, call the helper function to get the lng/lat, then add those values to the dictionary before initializing an Article. I also adjusted the error handling a bit to be more explicit instead of using try? (which can hide issues):
let task = session.dataTask(with: ArticlesUrl){(data,response,error) in if let error = error { print("Failed to fetch data: \(error.localizedDescription)") completionHandler(nil, error) return } guard let data = data else { let noDataError = NSError(domain: "DataFetchError", code: 1, userInfo: [NSLocalizedDescriptionKey: "No data received from server"]) completionHandler(nil, noDataError) return } do { guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any], let resultDict = jsonObject["result"] as? [String: Any], let articleArray = resultDict["results"] as? [[String: Any]] else { let parseError = NSError(domain: "JSONParseError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON structure"]) completionHandler(nil, parseError) return } var articles = [Article]() for articleDict in articleArray { // Make a mutable copy of the dict so we can add lng/lat var mutableDict = articleDict // Parse the geo coordinates if A_Geo exists if let geoString = articleDict["A_Geo"] as? String { let (lng, lat) = parseGeoCoordinates(from: geoString) mutableDict["lng"] = lng mutableDict["lat"] = lat } // Initialize Article with the updated dict let article = Article(rawData: mutableDict) articles.append(article) } completionHandler(articles, nil) } catch let parseError { print("JSON parsing failed: \(parseError.localizedDescription)") completionHandler(nil, parseError) } } task.resume()
3. Update your Article model
Make sure your Article class has properties to store the longitude and latitude, and that the initializer pulls those values from the raw data dict:
class Article { let articleID: String let nameChinese: String let location: String let nameEnglish: String let cid: String var longitude: Double? var latitude: Double? init(rawData: [String: Any]) { // Use nil-coalescing to fall back to empty strings if keys are missing self.articleID = rawData["_id"] as? String ?? "" self.nameChinese = rawData["A_Name_Ch"] as? String ?? "" self.location = rawData["A_Location"] as? String ?? "" self.nameEnglish = rawData["A_Name_En"] as? String ?? "" self.cid = rawData["A_CID"] as? String ?? "" // Pull the parsed lng/lat values self.longitude = rawData["lng"] as? Double self.latitude = rawData["lat"] as? Double } }
Quick notes
- The helper function handles cases where
A_Geomight be malformed (returns nil for both coords if parsing fails)—you can expand this to log errors or handle edge cases if needed. - I swapped out
try?for ado-catchblock and added explicit error handling for missing data/invalid JSON structure—this makes it easier to debug if something goes wrong. - The original JSON snippet you shared uses Chinese quotation marks (“”), but real JSON uses English ones (""), so the key names in the code are correct as-is.
内容的提问来源于stack exchange,提问作者Teddy Chen

