【问题标题】:Best method to parse consecutive JSON files?解析连续 JSON 文件的最佳方法?
【发布时间】:2016-11-15 14:12:32
【问题描述】:

我从一个链接导入 JSON,其中每个文件都包含一个“下一个”属性,其中包含下一个 JSON 文件的 URL,直到它最终为空并遍历所有文件。

我的问题是,我怎样才能最好地导入所有这些连续的文件?因为它们在表中都是必需的,但根据 API 限制,每个 JSON 的限制是 20 个对象。

我认为答案是循环遍历结果并声明“如果对象数为 20,则将 URL 页号增加 1”?那么一旦我到达最后一页并得到 8 个结果,它就会知道不要再循环了?我只是无法理解它在代码中的工作原理以及它的位置。

当前请求:

open class ApiService: NSObject {

open func getData(completionHandler: @escaping (NSDictionary?, NSError?) -> Void) -> Self {

    let requestUrl = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2&?limit=199"

    Alamofire.request(requestUrl, method: .get, encoding: URLEncoding.default)
        .responseJSON { response in

            switch response.result {

            case .success( let data):
                print("Request was sucessful")
                completionHandler(data as? NSDictionary, nil)

            case .failure(let error):
                print("Request failed with error: \(error)")
                completionHandler(nil, error as NSError?)
            }
    }
    return self
}

编辑更新:尝试在 cmets 中应用代码,这是我当前的代码,但我仍然有问题:

let requestUrl = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"

open func getData(_URL: NSURL, completionHandler: @escaping (NSDictionary?, NSError?) -> Void) -> Self {

Alamofire.request(requestUrl, method: .get, encoding: URLEncoding.default)
    .responseJSON { response in

        switch response.result {

        case .success(let data):
            print("Request was sucessful")

            let json = data as! [String:Any]

            let results = json["results"] as! NSDictionary; completionHandler(results, nil)

            if let nextURL = json["next"] as? NSURL {self.getData(_URL: nextURL, completionHandler: completionHandler)} else { print(json["next"] as? String)

                print("No next page, we are at the end")
            }

        case .failure(let error):
            print("Request failed with error: \(error)")
            completionHandler(nil, error as NSError?)
        }
}
return self

【问题讨论】:

  • 不计算对象。如果只有 40 个对象(根据您的请求组合),则不会有第三页。只需检查next 的值,然后重做。我建议将url 放在getData 的参数中,如果是.success,请检查if let next = data["next"], self.getData(URL.init(data["next"]) completionHandler:sameCompletionHandler)(在伪代码中)。
  • 有什么方法可以看到这应用于实际代码?我无法调整它以适应我的要求而没有错误
  • 我显然不是 Swift 开发人员,但我设法做了一些似乎可行的事情:print("Request was sucessful for \(url)"); let json = data as! [String:Any]; let results = json["results"] as! [[String:Any]]; completionHandler(results, nil); if let nextURL = json["next"] as? String {self.getData(_url: nextURL, completionHandler: completionHandler)}else{print(json["next"]); print("No next page, we are at the end")} 我敢肯定这不是 Swift 安全的,但你应该明白这一点。我给getData添加了一个参数url。
  • 我打了第一个电话:var arrayOfResults = [[String:Any]](); self.getData(_url: "https://wger.de/api/v2/exercise/?format=json&language=2&status=2&?limit=199") { (data: [[String : Any]]?, error: Error?) in arrayOfResults.append(contentsOf: data!); yourTableView.reloadData()}。相反,如果您使用UITableView,则可以重新加载它。如前所述,不是“Swift 安全”,但您应该明白这一点。
  • 有没有办法通过编辑我现有的 API 调用来做到这一点?这看起来大多是新代码?

标签: json swift api alamofire


【解决方案1】:

更新你的代码(我还没有编译过)

open class ApiService: NSObject {

open func getData(requestUrl: String, completionHandler: @escaping (NSDictionary?, NSError?) -> Void) -> Self {

    Alamofire.request(requestUrl, method: .get, encoding: URLEncoding.default)
        .responseJSON { response in

            switch response.result {

            case .success(let data):
                print("Request was sucessful")
                completionHandler(data as? NSDictionary, nil)

            case .failure(let error):
                print("Request failed with error: \(error)")
                completionHandler(nil, error as NSError?)
            }
    }
    return self
}
}

视图控制器中的代码

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let initialURLString = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
        getApiData(dataURL:initialURLString)
    }

func getApiData(dataURL: String) {

let _ = apiService.getData(requestUrl: dataURL) {
    (data, error) in
    if let data = data {
        if let results = data["results"] as? [[String:Any]] {
            for result in results {
                if let exercise = Exercise(dictionary: result) {
                    self.exercises.append(exercise)
                }
            }
            self.exercisesTableView.reloadData()
        }
        if let nextURL = data["next"] as? String
        {
            print("NEXT URL: \(nextURL)")
            self.getApiData(dataURL:nextURL)
        }
    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 2016-07-14
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    相关资源
    最近更新 更多