通信した結果をcollectionViewに表示したいのですが、うまくいきません。
まず、CollectionViewに表示するための情報をサーバーから取得し、表示します。
その後、表示したcellに対して、別のエンドポイントからもう一度情報を取得する必要があります。
その結果のBool値でicon画像の表示、非表示をしたいです。
表示したセル全てに対してAPIを叩くのですが、その際に必要なパラメーターがセクション番号とセル番号です。
cellが生成されるタイミングでindexpath.sectionとindexPath.cellを引数に入れて通信をするのですが、通信結果が帰って来る前に次の通信が走ってしまうので、うまくいきません。
通信結果が帰ってきてから次の通信を走らすためにはどうすれば良いのでしょうか?
swift
1// 省略 2 3func getAvailable(indexPath: IndexPath) { 4 // 通信処理 5 func download(section: indexPath.section, row: indexPath.row, completion: @escaping ((_ image:UIImage?) -> Void)) { 6 7 let url = xxxxxxxxxxxxxxxxxxxxxxxx 8 let urlRequest = URLRequest(url: URL(string: url)!) 9 10 let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in 11 if error != nil { 12 print(error as Any) 13 return 14 } 15 16 DispatchQueue.main.async { 17 // ここで帰ってきたデータからBool値を取得(パースした程です) 18 available = data as? Bool 19 } 20 } 21 task.resume() 22 } 23} 24 25// 省略 26 27extension ViewController: UICollectionViewDataSource { 28 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 29 5 30 } 31 32 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 33 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) 34 35 // 省略 36 37 let imageView = cell.viewWithTag(1) as? UIImageView 38 39 imageView?.image = Image 40 41 imageView.isHidden = available 42 43 return cell 44 } 45 46 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 47 48 let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Section", for: indexPath) 49 50 headerView.backgroundColor = UIColor.white 51 52 return headerView 53 } 54}
上記で間違ってる点とかあるかもしれませんがや、やりたいことはこんな感じのことです。
説明不足かもしれませんので、足りない部分があればおっしゃっていただければと思います。
調べてみて、排他制御をすればいいのかなと今は思っていますが、あまりしないほうがいいようなので、他に何か良い方法があれば教えていただければ助かります。
排他制御をしなくてはいけない場合、どのような実装が良いのかも教えていただければ助かります。
よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。