Download the image and asynchronously display the updated data to the foreground. There are many ways to do this. Two methods are mentioned in IOS as follows:
You need to define an imageview and a button as follows:
@property (retain, nonatomic) IBOutlet UIImageView *imageView;- (IBAction)download:(id)sender;
Method 1:
- (IBAction)download:(id)sender { NSURL *url = [NSURL URLWithString:@"http://img6.cache.netease.com/cnews/2012/6/1/20120601085505e3aba.jpg"]; [NSThread detachNewThreadSelector:@selector(dowork:) toTarget:self withObject:url]; }
The dowork function is called.
-(void) dowork: (NSURL*) url{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSError *error; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSHTTPURLResponse *response; NSData* retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (response.statusCode == 200) { UIImage* img = [UIImage imageWithData:retData]; [self performSelectorOnMainThread:@selector(refreshUI:) withObject:img waitUntilDone:YES]; } NSLog(@"d %d", response.statusCode); [pool drain]; }
The UI update is notified after the download is completed in the dowork method. The function is as follows:
-(void) refreshUI:(UIImage* ) img{ self.imageView.image = img;}
Method 2 Use GCD to update the UI
-(Ibaction) download :( ID) sender {[self blockwork];} the button calls the block method to download and callback async to asynchronously update the UI to display the image-(void) blockwork {dispatch_queue_t queue; queue = dispatch_queue_create ("com. example. operation ", null); dispatch_async (queue, ^ {nsstring * urlstring = @" http://img6.cache.netease.com/cnews/2012/6/1/20120601085505e3aba.jpg "; nsdata * imagedata = [nsdata datawithcontentsofurl: [nsurl urlwithstring: urlstring]; uiimage * imge = [uiimage imagewithdata: imagedata]; dispatch_async (dispatch_get_main_queue (), ^ {self. imageview. image = imge ;});});
Use block document:
Http://www.devdiv.com/blocksprogramming key words: Chinese translation moderator -article-3205-1.html