@ Property (weak, nonatomic) IBOutletUILabel * downLabelInfo;
@ Property (weak, nonatomic) IBOutletUIImageView * imageView;
@ End
@ ImplementationViewController
-(Void) viewDidLoad
{
[Super viewDidLoad];
NSString * url = @ "http://d.hiphotos.baidu.com/image/w%3D1366%3Bcrop%3D0%2C0%2C1366%2C768/sign=6cbcab9dabec8a13141a53e3c135aaec/aa64034f78f0f7369453c3730855b319ebc41316.jpg ";
@ Autoreleasepool {
NSThread * thread = [[NSThreadalloc] initWithTarget: selfselector: @ selector (downloadImage :) object: url];
[Thread start];
}
}
-(Void) didReceiveMemoryWarning
{
[Super didReceiveMemoryWarning];
}
-(Void) downloadImage :( NSString *) url {
// Put the displayed content in front of the synchronization method.
Self-> _ downLabelInfo. text = @ "downloading image ...";
// The synchronization method will be stuck in the thread until the completion position
NSData * imageData = [NSDatadataWithContentsOfURL: [NSURLURLWithString: url];
UIImage * image = [UIImageimageWithData: imageData];
If (image = nil)
{
}
Else
{
// Self-> _ downLabelInfo. text = @ "downloading image..."; so it is useless to write this statement.
[Self defined mselecw.mainthread: @ selector (updateImageView :) withObject :( image) waitUntilDone: YES];
}
}
-(Void) updateImageView :( UIImage *) image
{
Self-> _ imageView. image = image;
Self-> _ imageView. frame = CGRectMake (self. view. frame. size. width/2-100, self. view. frame. size. height/2-100,200,200 );
Self-> _ downLabelInfo. textColor = [UIColorredColor];
Self-> _ downLabelInfo. text = @ "image download completed ";
}
@ End
The second method is to use NSURLConnection sendSynchronousRequest to obtain and display the image content asynchronously.
Modify the downloadImage method as follows:
-(Void) downloadImage :( NSString *) url
{
Self-> _ downLabelInfo. text = @ "downloading image ...";
NSURLRequest * request = [NSURLRequestrequestWithURL: [NSURLURLWithString: url];
NSError * error;
NSData * data = [NSURLConnectionsendSynchronousRequest: requestreturningResponse: nilerror: & error];
If (data = nil)
{
NSLog (@ "nil ");
}
Else
{
UIImage * image = [UIImageimageWithData: data];
Self-> _ imageView. image = image;
Self-> _ downLabelInfo. textColor = [UIColorredColor];
Self-> _ downLabelInfo. text = @ "image download completed ";
}
}