ios - NSCache Doesn't work with all images when loading for the first time -
i'm woking on project in swift 3.0 cache response server using nscache populate them in uitableview. reason i'm seeing few images loading when app loads first time, if if scroll , come see (end of retrieving response server reload tableview too, seems not case). i'm not sure i''m missing here, code bellow show how cache images.
let imagecache = nscache<anyobject, anyobject>() var imageurlstring : string? extension uiimageview { public func imagefromserverurl(urlstring: string) { imageurlstring = urlstring if let url = url(string: urlstring) { image = nil if let imagefromcache = imagecache.object(forkey: urlstring anyobject) as? uiimage { self.image = imagefromcache return } urlsession.shared.datatask(with: url, completionhandler: { (data, response, error) in if error != nil{ print(error any) return } dispatchqueue.main.async(execute: { if let imgaetocache = uiimage(data: data!){ if imageurlstring == urlstring { self.image = imgaetocache } imagecache.setobject(imgaetocache, forkey: urlstring anyobject)// calls when scrolling } }) }) .resume() } } }
here images downloading , stored in cache fine. problem lies in updation of tableview cells.
when table view loading cells on table images not downloaded yet. once image downloaded have selectively update cell image displayed instantly.
since scrolling , tableview calls 'cellforrowatindexpath' again updates cell showing downloaded images while scrolling.
if still wish use extension , suggest add tableview , indexpath parameters can call reload specific row , have view updated instantly.
i have updated table reload code , structure of function defined in extension. let me know how goes.
let imagecache = nscache<anyobject, anyobject>() var imageurlstring : string? extension uiimageview { public func imagefromserverurl(urlstring: string, tableview : uitableview, indexpath : indexpath)) { imageurlstring = urlstring if let url = url(string: urlstring) { image = nil if let imagefromcache = imagecache.object(forkey: urlstring anyobject) as? uiimage { self.image = imagefromcache return } urlsession.shared.datatask(with: url, completionhandler: { (data, response, error) in if error != nil{ print(error any) return } dispatchqueue.main.async(execute: { if let imgaetocache = uiimage(data: data!){ if imageurlstring == urlstring { self.image = imgaetocache } imagecache.setobject(imgaetocache, forkey: urlstring anyobject)// calls when scrolling tableview.reloadrows(at: [indexpath], with: .automatic) } }) }) .resume() } }
Comments
Post a Comment