2016-11-12 62 views
0

我想将一个练习列表导入到tableview中。我有它的工作导入第一页,但这只是少数的练习。 JSON似乎有'下一页'链接,并且我希望能够在我开始加载过程时加载它们。处理多页JSON和TableView?

我需要使用某种if else语句来加载连续页面,如果它们存在,否则结束加载?

这是我的API服务

open class ApiService: NSObject { 

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

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

    Alamofire.request(requestUrl, method: .get, encoding: URLEncoding.default) 
     .responseJSON { response in 
      switch response.result { 
      case .success(let data): 

       completionHandler(data as? NSDictionary, nil) 

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

}

这是我的JSON,这显然参考了以下页面中的第一行

https://wger.de/api/v2/exercise/?format=json

这是我的桌面视图拉我的数据˚F相关

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
    if (searchActive){ 
     cell.textLabel?.text = filtered[indexPath.row] 
    } else { 
     if let row: NSDictionary = arrRes[indexPath.row] as NSDictionary? { 

      guard let name = row["name"] as? String else { 
       print("Fail") 
       return cell 
      } 
      cell.textLabel?.text = name 
     } 
    } 
    return cell 
} 

感谢一些建议!

回答

0

您可以在后台加载练习的下一页,然后在请求完成时将它们添加到结果数组(arrRes)。

然后,当你调用 tableView.reloadRows(at: [IndexPath], with: UITableViewRowAnimation)新成果的索引,表视图应该在动画的新成果。

+0

听起来不错,但我不知道如何做到这是最初的问题 – infernouk

0

你在这里做从JSON文件中获取的name属性相同的方式

guard let name = row["name"] as? String else { 
    print("Fail") 
    return cell 
} 

不管你想要去加载下一页这样做

// data is the json result you have from the first request 
func lookForNextPage(data: NSDictionary, completionHandler: @escaping (NSDictionary?, NSError?) -> Void) { 
    // Try and see if a next page exist 
    if let nextPage = data["next"] as? String { 
     // There is a next page, fetch it and add result to datasource 
     Alamofire.request(requestUrl, method: .get, encoding: URLEncoding.default) 
      .responseJSON { response in 
       switch response.result { 
       case .success(let data): 
        // Handle the new data as you wish 
        completionHandler(data as? NSDictionary, nil) 

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

嘛,只是它适应你的东东ds