iphone - How to download and set a UIImage not on the main thread -


i'm adding image web service. how code it's not on main thread? want view load first , image load user doesn't experience slowness when detail view controller loads.

what i'm unsure of how add dispatching code.

here's code far:

   nsdata *imagedata = [nsdata datawithcontentsofurl:[nsurl urlwithstring:mainimageurl]]; uiimage *image = [[uiimage alloc] initwithdata:imagedata];  uiview *v = [[uiview alloc] initwithframe:cgrectmake(10, 150, 300, 180)]; uiimageview *iv = [[uiimageview alloc] initwithframe:cgrectmake(0, 10, 300, 180)]; [iv setimage:image];  [_scrollview addsubview:v]; [v addsubview:iv]; 

and i'm thinking can use threading:

dispatch_async( dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ // add code here background processing // // dispatch_async( dispatch_get_main_queue(), ^{     // add code here update ui/send notifications based on     // results of background processing }); 

});

thanks help

you can use gcd download image this.

//your imageview uiimageview *iv = [[uiimageview alloc] initwithframe:cgrectmake(0, 10, 300, 180)]; // create __block type reference variable, arc use __weak instead __block uiimageview *blockimage = iv;  dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_high,  0ul); dispatch_async(queue, ^{     nsdata *imagedata=[nsdata datawithcontentsofurl:[nsurl urlwithstring:mainimageurl]];     dispatch_sync(dispatch_get_main_queue(), ^{         blockimage.image = [uiimage imagewithdata:imagedata];         // avoid retain cycle         blockimage = nil;     }); }); 

this code downloading image synchronously within gcd async block using datawithcontentsofurl: api, disadvantage cannot precise information when image fails download. in case handle error situations, use nsurlconnection asynchronously download image data.

also, suggested correctly in few of answers question, can use sdwebimage or afnetworking image view categories. give image cache facility , ensure image downloaded asynchronously without affecting main thread performance.

hope helps!


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -