快速合并两个api调用

问题描述 投票:0回答:1

我想在带有图像的表格视图中显示猫的品种。我有两个必须执行的api调用。第一个调用是获取所有品种"https://api.thecatapi.com/v1/breeds",然后我必须使用另一个api调用https://api.thecatapi.com/v1/images/search?breed_ids={breed_id}获取图像的URL。在该api调用之后,我得到一个必须下载的图像URL。

guard let url = URL(string: "https://api.thecatapi.com/v1/breeds") else {return}
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let dataResponse = data,
              error == nil else {
              print(error?.localizedDescription ?? "Response Error")
              return }
        do{
            let jsonResponse = try JSONSerialization.jsonObject(with:
                                   dataResponse, options: [])
            guard let breedArray = jsonResponse as? [[String: Any]] else {
                  return
            }
            for i in 0...breedArray.count-1{
                //This is where i make second api call and download image from url 
                let id = jsonArray[i]["id"] as! String
                // call https://api.thecatapi.com/v1/images/search?breed_ids=id
                // download image from ["url"] of that call. 
            }

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
         } catch let parsingError {
            print("Error", parsingError)
       }
    }

    task.resume()

我在遍历收到的品种数组时陷入困境。在执行与查找品种数组相同的过程时,我可以获取url,但这将非常长。从调用中获取图像网址并从第二个api下载图像的最快捷方法是什么?

ios swift url
1个回答
0
投票

这里是如何使用调度组进行多个URL调用的方法>>

 guard let url = URL(string: "https://api.thecatapi.com/v1/breeds") else {return}
        let group: DispatchGroup = DispatchGroup()
          group.enter()
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
           group.leave()
        guard let dataResponse = data,
                  error == nil else {
                  print(error?.localizedDescription ?? "Response Error")
                  return }
            do{
                let jsonResponse = try JSONSerialization.jsonObject(with:
                                       dataResponse, options: [])
                guard let breedArray = jsonResponse as? [[String: Any]] else {
                      return
                }
                for i in 0...breedArray.count-1{
                     group.enter()
                    //This is where i make second api call and download image from url 
                    let id = jsonArray[i]["id"] as! String
                    // call https://api.thecatapi.com/v1/images/search?breed_ids=id // And on response of this call .. you will call group.leave()
                    // download image from ["url"] of that call. 
                }


             } catch let parsingError {
                print("Error", parsingError)
           }
        }

        task.resume()

group.notify(queue: DispatchQueue.main) { [weak self] in
        self?.tableView.reloadData()
    }
© www.soinside.com 2019 - 2024. All rights reserved.