你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS-下載一張網絡圖片

iOS-下載一張網絡圖片

編輯:IOS開發綜合
效果圖:   源代碼連接:點擊打開鏈接   (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); }  
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved