dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
__block UIImage *image = nil;
dispatch_sync(concurrentQueue, ^{ /* Download the image here */
/* iPad's image from Apple's website. Wrap it into two
lines as the URL is too long to fit into one line */
NSString *urlAsString =
@"http://a.hiphotos.baidu.com/image/w%3D2048/sign=e9e1e60e5b82b2b7a79f3ec40595caef/b58f8c5494eef01f728c66cfe2fe9925bc317d1b.jpg";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSError *downloadError = nil;
NSData *imageData = [NSURLConnection
sendSynchronousRequest:urlRequest
returningResponse:nil
error:&downloadError];
if (downloadError == nil && imageData != nil){
image = [UIImage imageWithData:imageData];}
else if (downloadError != nil){
NSLog(@"Error happened = %@", downloadError); } else {
NSLog(@"No data could get downloaded from the URL.");
}
});
dispatch_sync(dispatch_get_main_queue(), ^{
/* Show the image to the user here on the main queue*/
if (image != nil){
/* Create the image view here */
UIImageView *imageView = [[UIImageView alloc]
initWithFrame:self.view.bounds];
[imageView setImage:image];
/* Set the image */
/* Make sure the image is not scaled incorrectly */
[imageView setContentMode:UIViewContentModeScaleAspectFit]; /* Add the image to this view controller's view */
[self.view addSubview:imageView];
} else {
NSLog(@"Image isn't downloaded. Nothing to display.");
} });
});
GCD
最新推荐文章于 2024-05-28 18:43:15 发布