ios - Swift Async Imageloader -
i implement tableview cells display image. images loaded asynchroniously. better scrolling want request canceled if cell scrolls out of view. code far works, don't know how detect if cell visible or "scrolled over".
here's code:
func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecellwithidentifier("eventstablecell", forindexpath: indexpath) as! eventstablecell var elem : event = data[indexpath.row] event cell.headlinelabel.text = elem.getname() cell.secondlabel.text = elem.getdescription() cell.progressview.setprogress(0.0,animated: true) if let image = imagecache.getimage(elem.getid()) { cell.coverimage.image = image cell.progressview.removefromsuperview() } else { cell.coverimage.image = uiimage(named: "loading") if(elem.getcover() == nil){ //noimage cell.progressview.removefromsuperview() }else{ println("start request for" + elem.getname()!) cell.request = alamofire.request(.get, elem.getcover()!) .progress { (_, totalbytesread, totalbytesexpectedtoread) in dispatch_async(dispatch_get_main_queue()) { // 6 cell.progressview.setprogress(float(totalbytesread) / float(totalbytesexpectedtoread), animated: true) // 7 if totalbytesread == totalbytesexpectedtoread { cell.progressview.removefromsuperview() } } } .response { (request, response, data, error) in if error == nil && cell.coverimage.image != nil { imagecache.addimage(elem.getid(),image: uiimage(data: data!, scale:1)!) cell.coverimage.image = uiimage(data: data!, scale:1) }else{ } } } } return cell }
and following code can cancel request:
cell.request!.cancel()
i noticed progressview isn't displayed sometimes, or maybe deleted superview early, maybe can help.
thanks tobias
cells reused table view performance reasons. same cell used lot of time different indexpath.
following line
tableview.dequeuereusablecellwithidentifier("eventstablecell", forindexpath: indexpath) as! eventstablecell
creates new eventstablecell object if there no 1 reused!
so progressview
issue clear - remove cell calling
cell.progressview.removefromsuperview()
but never add it. example add right after dequeuereusablecellwithidentifier
call , remove later if needed. think in case better not remove/add hide/show instead:
cell.progressview.hidden = false
quite same image request - can call
cell.request?.cancel()
just after dequeuereusablecellwithidentifier
to make code more obvious can cancel in prepareforreuse method of eventstablecell have same effect.
prepareforreuse
prepares reusable cell reuse table view's delegate.
Comments
Post a Comment