【问题标题】:Filtering an API Request Response by an object array?通过对象数组过滤 API 请求响应?
【发布时间】:2017-05-25 05:56:17
【问题描述】:

我正在为与锻炼相关的肌肉进行 API 调用,调用如下所示:

    func loadPrimaryMuscleGroups(primaryMuscleIDs: [Int]) {
    print(primaryMuscleIDs)
    let url = "https://wger.de/api/v2/muscle"
    Alamofire.request(url).responseJSON { response in
        let jsonData = JSON(response.result.value!)
        if let resData = jsonData["results"].arrayObject {
            let resData1 = resData as! [[String:AnyObject]]
            if resData1.count == 0 {
                print("no primary muscle groups")
                self.musclesLabel.isHidden = true
            } else {
                print("primary muscles used for this exercise are")
                print(resData)
                self.getMuscleData(muscleUrl: resData1[0]["name"] as! String)
            }
        }
    }
}

这会返回给我所有可用肌肉的完整列表,我需要它来返回锻炼所需的肌肉。这在练习中显示为一组肌肉 ID,我通过下面的 viewDidLoad 输入

self.loadPrimaryMuscleGroups(primaryMuscleIDs: (exercise?.muscles)!)

所以我将锻炼肌肉阵列作为 [Int] 输入到 func 中,但此时我不知道如何过滤请求,以便生成的肌肉数据只是锻炼所需的数据。

我在想这就像在 jsonData 响应中使用 primaryMuscleIDs 过滤肌肉的 id 属性,但我不知道该怎么做?

感谢您在这里的任何澄清,希望我已经解释得足够清楚了

【问题讨论】:

  • 您是否已经实现了具有arrayObject 属性的JSON() 对象?
  • 我相信它来自 swiftyJSON

标签: ios json swift api alamofire


【解决方案1】:

你想在你的 else 块中做这样的事情:

var filteredArray = resData1.filter { item in
    //I'm not exactly sure of the structure of your json object,
    //but you'll need to get the id of the item as an Int
    if let itemId = item["id"] as? Int  {  
        return primaryMuscleIDs.contains(itemId)
    }
    return false
}

//Here with the filtered array

由于Alamofire 请求是异步的,您将无法同步返回结果。您的方法需要采用一个回调,该回调在 Alamofire 响应回调中执行,并带有过滤后的响应。

类似的东西(但希望比Any的数组更具描述性:

func loadPrimaryMuscleGroups(primaryMuscleIDs: [Int], callback: ([Any]) -> ()) {
    //...
    Alamofire.request(url).responseJSON { response in
        //...
        //once you get the filtered response:
        callback(filteredArray)
    }
}

最后,查看How to parse JSON response from Alamofire API in Swift?,了解处理来自Alamofire 的 JSON 响应的正确方法。

【讨论】:

  • 感谢我只是试图整合它的评论,如果它有助于回答wger.de/api/v2/muscle,您可以在此处找到肌肉 JSON 对象我有一个单独的获取功能,用于 alamofire 我没有包含在问题中这只是关于目前的过滤
猜你喜欢
  • 2022-11-27
  • 2021-05-02
  • 2018-11-03
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 2019-12-02
相关资源
最近更新 更多