效果圖:
源代碼連接:點擊打開鏈接
(1) 在ViewController.h裡面關聯一個imageview和一個button
@property (weak, nonatomic) IBOutletUIImageView *showImageView;
- (IBAction)loadImage:(id)sender;
(2)在ViewController.m裡面
第一種方法:
- (IBAction)loadImage:(id)sender {
NSURL *url = [NSURLURLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
dispatch_queue_t queue =dispatch_queue_create("loadImage",NULL);
dispatch_async(queue, ^{
NSData *resultData = [NSDatadataWithContentsOfURL:url];
UIImage *img = [UIImageimageWithData:resultData];
dispatch_sync(dispatch_get_main_queue(), ^{
self.showImageView.image = img;
});
});
}
第二種方法:
- (IBAction)loadImage:(id)sender {
NSURL *url = [NSURLURLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
NSData *resultData = [NSDatadataWithContentsOfURL:url];
UIImage *img = [UIImageimageWithData:resultData];
self.showImageView.image = img;
}
第三種方法(異步下載:):
ViewController.h
@property(nonatomic,retain)NSMutableData *mutableData;
@property (weak, nonatomic) IBOutletUIImageView *showImageView;
- (IBAction)loadImage:(id)sender;
ViewController.m
- (IBAction)loadImage:(id)sender {
NSURL *url = [NSURLURLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] init];
[requestsetURL:url];
[requestsetHTTPMethod:@"GET"]; //設置請求方式
[request setTimeoutInterval:60];//設置超時時間
self.mutableData = [[NSMutableDataalloc] init];
[NSURLConnectionconnectionWithRequest:request delegate:self];//發送一個異步請求
}
#pragma mark - NSURLConnection delegate
//數據加載過程中調用,獲取數據
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.mutableDataappendData:data];
}
//數據加載完成後調用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
UIImage *image = [UIImageimageWithData:self.mutableData];
self.showImageView.image = image;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"請求網絡失敗:%@",error);
}