各セルに画像があるカスタムセルでtableViewを作成しました。モデルクラスの画像をテーブルビューで表示することはできません
は、私は、URLからデータを取得し、完了ハンドラブロックにUIImage
にデータを変換し、その後、UIImage
の配列の変数に画像を追加するURLSession
dataTaskメソッドを使用するfunc mainPulatesData()
を作成しました。
データを取り出してUIImage
アレイに追加するプロセスは、DispatchQueue.global(qos: .userInitiated).async
ブロックで実行されました。印刷メッセージに基づいて、画像がアレイに追加された。
しかし、テーブルビューコントローラでモデルクラスのインスタンスを作成してmainPulatesData()
をviewDidlLoad
に呼び出しても、その画像はテーブルに表示されませんでした。
テーブルビューコントローラクラスの他の印刷メッセージに基づいて、モデルクラスの配列に追加することもできますが、tableViewコントローラのモデルクラスのインスタンスでは動作しないようです。
func mainPulatesData() {
let session = URLSession.shared
if myURLs.count > 0{
print("\(myURLs.count) urls")
for url in myURLs{
let task = session.dataTask(with: url, completionHandler: { (data,response, error) in
let imageData = data
DispatchQueue.global(qos: .userInitiated).async {
if imageData != nil{
if let image = UIImage(data: imageData!){
self.imageList.append(image)
print("\(self.imageList.count) images added.")
}
}
else{
print("nil")
}
}
})
task.resume()
}
}
}
モデルのインスタンスを作成するためのビューコントローラのコードです:
override func viewDidLoad() {
super.viewDidLoad()
myModel.mainPulatesURLs()
myModel.mainPulatesData()
loadImages()
}
private func loadImages(){
if myModel.imageList.count > 0{
tableView.reloadData()
}
else{
print("data nil")
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myModel.imageList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath) as! ImageTableViewCell
if myModel.imageList.count > 0{
let image = myModel.imageList[indexPath.row]
cell.tableImage = image
return cell
}
return cell
}
これは遅延読み込みの概念です。これについては、SDWebImage(サードパーティのライブラリ) –