ios - Saving image from a URL asynchronously -
so have gone through questions on so, , have put them create method accepts 2 paramaters, first url
of image download , display in uiimageview
, second placeholder image uiimageview
. want save image won't downloaded every time. have used sdwebimage download image, had confusion when came saving image in documents directory using sdwebimage, decided not use it. used dispatch_sync(dispatch_get_main_queue()
, method looks :
- (void)saveimagefromurl:(uiimage*)image:(nsurl*)imageurl { nsstring *url = [imageurl absolutestring]; nsarray *parts = [url componentsseparatedbystring:@"/"]; nsstring *filename = [parts lastobject]; nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; nsstring *fullpath = [documentsdirectory stringbyappendingpathcomponent:[nsstring stringwithformat:@"%@.png", filename]]; bool fileexists = [[nsfilemanager defaultmanager] fileexistsatpath:fullpath]; if (fileexists) { nslog(@"file exists"); _myuiimage.image = [uiimage imagenamed:fullpath]; return; } else { dispatch_async(dispatch_get_main_queue(), ^{ [self.myuiimage sd_setimagewithurl:imageurl placeholderimage:image]; uiimage *imagefromurl = [uiimage imagewithdata:[nsdata datawithcontentsofurl:imageurl]]; nsdata *imagedatanew = uiimagepngrepresentation(imagefromurl); nsfilemanager *filemanager = [nsfilemanager defaultmanager]; [filemanager createfileatpath:fullpath contents:imagedatanew attributes:nil]; }); } }
i have couple of questions, implementation enough since working on app on app store ? downloading of image url done asynchronously ? (i know using dispatch_async
need confirm). if yes, wont block ui, right ?
dispatch_async(dispatch_get_global_queue( dispatch_queue_priority_default, 0), ^(void){ // *** load image url asynchronously without blocking main thread *** uiimage *imagefromurl = [uiimage imagewithdata:[nsdata datawithcontentsofurl:imageurl]]; dispatch_async(dispatch_get_main_queue(), ^(void){ // *** create file path documentdirectory *** nsstring * docdirpath = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes)[0]; nsstring *filepath = [docdirpath stringbyappendingpathcomponent:@"myimage.jpg"] // *** write image disk *** bool issaved = [uiimagejpegrepresentation(image, 1.0f) writetofile:dirpath atomically:yes]; if(issaved) { nslog(@"image write disc successfully."); } }); });
Comments
Post a Comment