You need to enable JavaScript to run this app. iOS解码MapBox API JSON响应:如何单独存储features数组的每个Feature对象
优惠活动
大模型
产品
解决方案
定价
更多

iOS解码MapBox API JSON响应:如何单独存储features数组的每个Feature对象

问题解决方法

错误根源

你目前的代码在解析完整个MapBox响应后,直接将整个包含所有features的Response对象添加到了suggestedPlacenames数组中,而非遍历features数组逐个添加每个Feature对象,因此无论返回多少条地点数据,数组长度始终为1。
另外还有两处潜在问题需要注意:

  • 你的Properties Codable模型定义和MapBox实际返回的字段不匹配(返回的是wikidata、short_code,没有address字段,虽然可选值不会导致解码失败,但后续取值会异常)
  • 网络请求的回调默认在后台线程执行,直接修改数组后刷新表格会触发UI渲染异常,需要切回主线程处理。
  • 原代码创建了网络请求Task后未调用resume()启动任务,实际开发中需要补上该逻辑。

具体调整步骤

  1. 先修正Codable模型的字段定义(按需保留你需要的字段即可):
struct Response: Codable {
    var features: [Feature]
}

struct Feature: Codable {
    var id: String
    var type: String?
    var matching_place_name: String?
    var place_name: String?
    var geometry: Geometry
    var center: [Double]
    var properties: Properties
}

struct Geometry: Codable {
    var type: String?
    var coordinates: [Double]
}

// 修正为MapBox实际返回的字段
struct Properties: Codable {
    var wikidata: String?
    var short_code: String?
}
  1. 调整解码后的数组添加逻辑,遍历features逐个入列,同时补充主线程刷新逻辑:
var suggestedPlacenames: NSMutableArray = []
func doShowSuggestion(usersQuery: String) {
    let urlString = "\(mapbox_api)\(usersQuery).json?access_token=\(mapbox_access_token)"
    guard let url = URL(string: urlString) else { return }
    let task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
        guard let self = self else { return }
        // 清空旧的搜索建议避免重复拼接
        self.suggestedPlacenames.removeAllObjects()
        guard let data = data, error == nil else {
            print("Error in URLSession")
            return
        }
        do {
            let result = try JSONDecoder().decode(Response.self, from: data)
            // 遍历features数组,逐个添加每个Feature对象到数组
            result.features.forEach { feature in
                self.suggestedPlacenames.add(feature)
            }
            // 切回主线程刷新表格UI
            DispatchQueue.main.async {
                self.tableView.reloadData() // 替换为你实际的tableView实例
            }
        } catch {
            print("解码失败: \(error)")
        }
    }
    // 启动网络请求
    task.resume()
}

额外优化建议

如果你的项目支持,更推荐用Swift原生的类型安全数组替代NSMutableArray,避免类型强制转换的隐患:

// 替换NSMutableArray的定义
var suggestedPlacenames: [Feature] = []

对应的添加逻辑直接用self.suggestedPlacenames = result.features即可,不需要遍历逐个添加。


内容的提问来源于stack exchange,提问作者mefahimrahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 18:24:04