2017-12-11 21 views
0

私はs3バケットから画像をロードし、セル内の画像でデータを設定するテーブルビューを持っています。S3バケットからuiTableViewに画像をロード

は、私は私のtableviewcellに

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cellDish:DishTableViewCell = tableView.dequeueReusableCell(withIdentifier: "DishCell", for: indexPath) as! DishTableViewCell 

    cellDish.setDish(dish: brain.listOfDishes[indexPath.row]) 


    return cellDish } 

で私のセルを呼び出す私はFUNCと呼ばれるsetDishあります

func setDish (dish: Dish) 
{ 
    var StringPrice = dish.DishPrice 
    StringPrice.append("$") 
    self.la_name.text = dish.DishName 
    self.la_price.text = StringPrice 
    self.la_des.text = dish.DishDes 
    self.downloadData(dish: dish, completion: { success in 
     guard success else { return } 
     DispatchQueue.main.async {  
      self.dish_image.image = UIImage(data: dish.DishData!)! 

     } 
    }) 


} 


func downloadData(dish:Dish,completion: @escaping (Bool) -> Void) { 
    let transferUtility = AWSS3TransferUtility.default() 
    let expression = AWSS3TransferUtilityDownloadExpression() 
    let s3Bucket = "<my bucket name>" 

    transferUtility.downloadData(fromBucket: s3Bucket, key: dish.DishImage, expression: expression) {(task, url, data, error) in 
     if error != nil {print(error) 
      completion(false) 
     } 
     else { 

      dish.DishData = data! 

     } 
     completion(true) 
    } 

} 

私はイメージがダウンロードされるまで、それは画像なしで私の料理データを表示したいのそれを私にも見せてください(私はそれがもちろんメインスレッドではないことを望みます)。 私は理由は分かりませんが、今はすべてのセルが画像をダウンロードして、すべてが一緒に読み込まれます。

+0

: ロードURLの非同期が自動的

extension UIImageView { public func imageFromServerURL(urlString: String) { URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in if error != nil { print(error) return } DispatchQueue.main.async(execute: {() -> Void in let image = UIImage(data: data!) self.image = image }) }).resume() }} 

スウィフト2.2のコードを更新します。それは、画像の非同期ダウンロードに役立ちます。プレースホルダはダウンロード中に設定できます。 https://github.com/onevcat/Kingfisher –

+0

'downloadData'のどのスレッドが動作しているのか分かりますか? – creeperspeak

+0

私はそれがメインではないことを知っている –

答えて

0

スウィフト3更新されたコード:このライブラリーをチェックしてください

extension UIImageView { 
     public func imageFromServerURL(urlString: String) { 

      NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in 

       if error != nil { 
        print(error) 
        return 
       } 
       dispatch_async(dispatch_get_main_queue(), {() -> Void in 
        let image = UIImage(data: data!) 
        self.image = image 
       }) 

      }).resume() 
     }} 
関連する問題