пятница, 12 июля 2013 г.

iOS Image Loader. Загрузка картинок.

В этой статье я покажу как пользоваться небольшой библиотечкой ( собственной разработки ) для загрузки картинок. Так как все время копировать код и подправлять немного мне надоело, решил написать загрузку с простым кэшированием картинок. Сделал так чтобы можно было подключить как говорится в один клик. Библиотека называется DLImageLoader.

Создаем проект. Добавляем в него библиотеку.

Я покажу пример на UITableView.
Наследуем ViewController от UITableViewController.
Изменяем класс ViewController должно получиться примерно вот так:

 #import "ViewController.h"  
 #import "DLImageLoader.h"  

 @interface ViewController ()  

 @property (nonatomic, strong) NSArray *urls;  

 @end  

 @implementation ViewController  

 - (id)initWithStyle:(UITableViewStyle)style {  
   self = [super initWithStyle:style];  
   if (self) {  
     // Custom initialization  
   }  
   return self;  
 }  
 
- (void)viewDidLoad {  
   [super viewDidLoad];  
   self.urls = [NSArray arrayWithObjects:@"url to image here", nil];  
 }  

 - (void)didReceiveMemoryWarning {  
   [super didReceiveMemoryWarning];  
   // Dispose of any resources that can be recreated.  
 }  

 #pragma mark - Table view data source  

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {  
   return 1;  
 }  

 - (NSInteger)tableView:(UITableView *)tableView  
  numberOfRowsInSection:(NSInteger)section {  
   return [self.urls count];  
 }  

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
   static NSString *CellIdentifier = @"Cell";  
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
   if (cell == nil) {  
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  
                    reuseIdentifier:CellIdentifier];  
   }  
   // Configure the cell...  
   cell.imageView.image = nil;  
   [[DLImageLoader sharedInstance] loadImageFromURL:[self.urls objectAtIndex:indexPath.row]  
                         completed:^(NSError *error, NSData *imgData) {  
                             cell.imageView.image = [UIImage imageWithData:imgData];  
                             [cell setNeedsLayout];  
   }];  
   return cell;  
 }  
 @end  

Вот и все.



Библиотека c полным примером -> DLImageLoader-iOS