UITableView displaying webImages in Swift languages seems to freeze

420 Views Asked by At

so i'm kind of a noobe to iOS and Swift also (actually only one month and a half). So I'm trying to make a tableview displaying some images coming from the web, I managed to get the correct info from a web API and display them in the tableview. But, the tableview with online images seems to freeze, I should wait 2-3 seconds for it to move just a little bit and freeze again, which is very frustrating. I know it has something to do with synchronize, I also tried dispatch_async(dispatch_get_main_queue()){}, and since I'm developing with Swift not ObJ, I tried an open source Web Image download helper from Github called Kingfisher, but it didn't solve my problem. So, please, help me, and thanks. To keep it simple, here's the demo code:

var arrays = [
"NPWR02174_00_013F09F4AE3D70230FA695261A8E994D275DF62333/C878A05EF327D7D42E2AF5E1EE15672A1509962C.PNG",
"NPWR04270_00_01C53CAC0BACAC6F052AE4B968370CF9B899DDA81E/C1E1A8AD62EDE2FB95C3BD562F2783F157A0D011.PNG",
"NPWR04472_00_01CB90FF28A2EBB55D210932F56935B377E7A28ECB/DCA2F66365777A7330F685CD8CD5F90F2FE62671.PNG",
"NPWR04841_00_017B982A2A44BB607DECD77484C4670CCB505B65E4/91824E16D16C2789CC34A2F5F5444CD30D71C8F1.PNG",
"NPWR05212_00_018ADD99CEA95C240EFDC92FB993F6BC8C0AF7904D/7266E29159EE69D31AA24FB94BC0E90F5306774A.PNG",
"NPWR05254_00_015EB28BB38A5580D6A73CA0BDFB2F8C6864F85F66/76ED779ECE98E63E8A1A229AE626F62E8325D703.PNG",
"NPWR05257_00_01CB48AFF2A9F0795B5569E1DABBC612E3FA13B79A/3524288D6B1E5B4F51CF7DEA4A3E621913A1BA8C.PNG",
"NPWR05326_00_01DF67B968910B06FDABD8A2C2C6AAB72E0DD47048/8AB6EC3EC992C35472F02DD0C8D4122302C802E1.PNG",
"NPWR05401_00_0188285B6025E65909B39E295D2542DF589EDCCC38/620822A98E3CFC1CFB3B5EDCF3F00B19A5B328C2.PNG",
]

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

    return arrays.count

}

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = self.tableview.dequeueReusableCellWithIdentifier("gameCell")!
    dispatch_async(dispatch_get_main_queue()){
        let image = cell.viewWithTag(101) as! UIImageView

    let imageString = arrays[indexPath.row] as! String

    let imageURL = NSURL(string: "https://trophy01.np.community.playstation.net/trophy/np/"+imageString)!

    let data = NSData(contentsOfURL: imageURL)!

        image.image = UIImage(data: data)}

    return cell

}
1

There are 1 best solutions below

2
Saroj On

It is because you are downloading the image synchronously. This is the code line that does so.

let data = NSData(contentsOfURL: imageURL)

Try downloading the image asynchronously and then update the cell once image is downloaded. Checkout this answer How to async load images on dynamic UITableView?