-1

我知道这很常见,但找不到答案。我想过使用 dispatchGroups 但不知道我该怎么做

要求:API 1 给出 id,我需要用那个 id 构造 url 并调用另一个 API 来获取 imageUrl,然后用 imageUrl 构建结构

struct Item {
 let itemId: String?
 let quantity: String?
 let itemImageUrl: String?
}

struct InitialDetails: Codable {
  let id: String
  let quantity: String
}

struct ImagePathData: Codable {
 let imageUrl: String
}

接口 1:

{ 
 items: [{
   id: "1",
   quantity: "10"
}]
}

API 2

{
itemImagePath: "https://itemizedUrl/fish.png"
}

代码

func fetchData() -> [Item] {
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        var items: [Items] = []
        let initialData = try JSONDecoder().decode([InitialDetails].self, from: data)
        for info in initialData {
            var imageUrlPath: String?
            let imageDataUrl = "https://itemizedUrl.com/\(info.id)"
            URLSession.shared.dataTask(with: imageDataUrl) { (data, response, error) in
                imageUrlPath = try JSONDecoder().decode(ImagePathData.self, from data)
            }
            let item = Item(itemId: initialData.id,
                  quantity: initialData.quantity,
                  itemImageUrl: imageUrlPath)
            items.append(item)
        }
        return items
     }
}

我知道这是不对的..请建议我如何实现这种情况

4

1 回答 1

0

您需要使用 dispachGroup 完成

func fetchData(completion:@escaping([Item]) -> ()) { 
  var items: [Items] = []
  let g = DispatchGroup()
  URLSession.shared.dataTask(with: url) { (data, response, error) in
  do {
  let initialData = try JSONDecoder().decode([InitialDetails].self, from: data)
  for info in initialData {
   g.enter() 
   let imageDataUrl = "https://itemizedUrl.com/\(info.id)"
   URLSession.shared.dataTask(with: imageDataUrl) { (data, response, error) in
     do {
     let imageUrlPath = try JSONDecoder().decode(ImagePathData.self, from data)
         let item = Item(itemId: initialData.id,
                  quantity: initialData.quantity,
                  itemImageUrl: imageUrlPath.imageUrl)
        items.append(item)
        g.leave()
        } catch { 
         print(error)
        }
   } 
  }
  } catch  {  
     print(error)
  }
  g.notify(queue:.main) {
    completion(items)
  }
 }
}
于 2020-08-18T23:51:01.187 回答