Search code examples
iosswiftuitableviewalamofiresdwebimage

UITableIViewCell image downloading from URL


I am downloading images from URL using alamofire. I am getting Images onclick but not while view is appearing.
How to get all images while view appears? This is the code I am using to achieve that:

import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage
import Kingfisher

class Paragogoi: UITableViewController {
var data=[FronItem]()   

override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request(.GET, "http://gaiaskarpos.com/getCategores.php").validate().responseJSON { response in
        switch response.result {
        case .Success:
            if let value = response.result.value 
            {
                let json = JSON(value)

                let list: Array<JSON> = json.arrayValue
                var urls=[String]()

                for element in list{
                    let id:String=element["id"].stringValue
                    let name:String=element["name"].stringValue
                    let url:String=element["url"].stringValue
                     self.data.append(FronItem(id:id,name:name,url:url))

                };
                self.tableView.reloadData() 

            }
        case .Failure(let error):
            print(error)
        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return data.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("paragogosCell", forIndexPath: indexPath)

    cell.textLabel?.text = data[indexPath.row].name

    asycloadp(data[indexPath.row].url!, imageView: cell.imageView!)


    return cell
}

func asycloadp(url:String,imageView:UIImageView){
    let downloadQueue=dispatch_queue_create("myqueue", nil)

    print(url)
    dispatch_async(downloadQueue){
        let imageUrl:NSURL?
        = NSURL(string:url)
        dispatch_async(dispatch_get_main_queue()){
        imageView.sd_setImageWithURL(imageUrl)
        }

    }
}

}

Should I add anything other than This?


Solution

  • Because dispatch_async is asynchronous transmission, you have to refresh table view after downloading image, but I see that you are using SDWebImage, then you don't need funciton asycloadp, change your code and try again.

    import UIKit
    import Alamofire
    import SwiftyJSON
    import SDWebImage
    import Kingfisher
    
    class Paragogoi: UITableViewController {
        var data=[FronItem]()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            Alamofire.request(.GET, "http://gaiaskarpos.com/getCategores.php").validate().responseJSON { response in
                switch response.result {
                case .Success:
                    if let value = response.result.value {
                        let json = JSON(value)
    
                        let list: Array<JSON> = json.arrayValue
                        var urls=[String]()
    
                        for element in list{
                            let id:String=element["id"].stringValue
                            let name:String=element["name"].stringValue
                            let url:String=element["url"].stringValue
                            self.data.append(FronItem(id:id,name:name,url:url))
    
                        };
                        self.tableView.reloadData()
    
                    }
                case .Failure(let error):
                    print(error)
                }
            }
    
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
        override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
            return data.count
        }
    
    
        override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("paragogosCell", forIndexPath: indexPath)
    
            cell.textLabel?.text = data[indexPath.row].name
    
            let imageUrl:NSURL? = NSURL(string:url)
            cell.imageView!.sd_setImageWithURL(imageUrl,  completed:{(image: UIImage?, error: NSError?, cacheType: SDImageCacheType!, imageURL: NSURL?) in
                if (image != nil) {
                    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
                }
            })
    
            return cell
        }
    
    }