解析连续JSON文件的最佳方法?

时间:2016-11-15 14:12:33

标签: json swift api alamofire

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

我的问题是,我怎样才能最好地导入所有这些连续文件?因为它们在表中都是必需的,但根据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
}

编辑更新:如果要在评论中应用代码,这是我当前的代码,但我仍有问题:

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

1 个答案:

答案 0 :(得分: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
}
}

View Controller中的代码

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)
        }
    }
}
}