2014-12-10 1 views
0

Я делаю приложение, в котором я получаю данные с сервера, а также путь к пути передачи данных также приходит, но когда я устанавливаю изображение в мое приложение для просмотра таблицы, станет слишком много может би я не устанавливая изображение правильно ниже мой пример кода спасибо заранее :)Как установить путь изображения от сервера в uitableviewcell

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    static NSString *tableviewidentifier = @"cell"; 
    tablecellTableViewCell *cell= [self.activitiesTableView_ dequeueReusableCellWithIdentifier:tableviewidentifier]; 

    if(cell==nil) 
    { 
     cell = [[tablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableviewidentifier]; 
    }if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1){ 
     // [[cell textLabel] setText:@"Load more records"]; 
    } 

    UILabel *valuedate = (UILabel *)[cell viewWithTag:21]; 
    UILabel *msg = (UILabel *)[cell viewWithTag:22]; 
    UILabel *date = (UILabel *)[cell viewWithTag:23]; 
    UILabel *time = (UILabel *)[cell viewWithTag:24]; 
    valuedate.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"offerTitle"]; 
    [email protected]"How are you?"; 
    NSString *img=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"offerPhoto"];// here i am getting image path 
    UIImage *img1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; 
    cell.imageView.image=img1;// here i am setting image due to which app is so heavy and stuck 


    return cell; 
} 
+0

Что такое значение: NSString * IMG. Добавьте его как ссылку, вы можете получить это из NSLog. – Mrunal

+0

проверить мой ответ, я отредактировал .. –

ответ

1

попробуйте этот код ниже, надейтесь, что это поможет вам.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    __block tablecellTableViewCell *cell= [self.activitiesTableView_ dequeueReusableCellWithIdentifier:tableviewidentifier]; 
    if(cell==nil) 
    { 
     cell = [[tablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableviewidentifier]; 
    } 
    if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1) 
    { 
     // [[cell textLabel] setText:@"Load more records"]; 
    } 
    UILabel *valuedate = (UILabel *)[cell viewWithTag:21]; 
    UILabel *msg = (UILabel *)[cell viewWithTag:22]; 
    UILabel *date = (UILabel *)[cell viewWithTag:23]; 
    UILabel *time = (UILabel *)[cell viewWithTag:24]; 
    valuedate.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"offerTitle"]; 
    [email protected]"How are you?"; 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{  
    NSString *img=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"offerPhoto"];// here i am getting image path 
    NSURL *url = [NSURL URLWithString:img]; 
    NSData * imageData = [NSData dataWithContentsOfURL:url]; 
    UIImage *image = [UIImage imageWithData:imageData]; 

    dispatch_sync(dispatch_get_main_queue(), ^{ //in main thread update the image 
    cell.imageView.image = image; 
    cell.textLabel.text = @""; //add this update will reflect the changes 
    }); 
    }); 
return cell; 
} 

EDIT для повторного использования загруженного изображения и может либо сохранить их на диск или просто сохранить их немного, где, например, в словаре для временного использования

ниже в коде я взял один пример словарь, и сильные Загружать изображения строки как ключевой

@interface ViewController() 
{ 
    NSMutableDictionary *imagesDictionary; //lets declare a mutable dictionary to hold images 
} 

в этом методе просто инициализирует его

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // rest of your code 
    //........... 
    // 
    imagesDictionary = [[NSMutableDictionary alloc]init]; //initilise 
} 

в индексе этот метод просто добавить загруженные изображения в словарь для соответствующей строки в качестве ключа

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
    __block tablecellTableViewCell *cell= [self.activitiesTableView_ dequeueReusableCellWithIdentifier:tableviewidentifier]; 
    if(cell==nil) 
    { 
     cell = [[tablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableviewidentifier]; 
    } 
    if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1) 
    { 
     // [[cell textLabel] setText:@"Load more records"]; 
    } 
    __block NSString *row = [NSString stringWithFormat:@"%d",indexPath.row]; //add this 

    UILabel *valuedate = (UILabel *)[cell viewWithTag:21]; 
    UILabel *msg = (UILabel *)[cell viewWithTag:22]; 
    UILabel *date = (UILabel *)[cell viewWithTag:23]; 
    UILabel *time = (UILabel *)[cell viewWithTag:24]; 
    // valuedate.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"offerTitle"]; 
    [email protected]"How are you?"; 
    if(![[imagesDictionary allKeys] containsObject:row]) //if image not found download and add it to dictionary 
    { 
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ 
     // NSString *img=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:@"offerPhoto"];// here i am getting image path 
     NSURL *url = [NSURL URLWithString:img]; 
     NSData * imageData = [NSData dataWithContentsOfURL:url]; 
     UIImage *image = [UIImage imageWithData:imageData]; 

     dispatch_sync(dispatch_get_main_queue(), ^{ //in main thread update the image 
      [imagesDictionary setObject:image forKey:row]; //sorry, while editing to your code i forgot to add this 
      cell.imageView.image = image; 
      cell.textLabel.text = @""; //add this update will reflect the changes 
      NSLog(@"loading and addig to dictionary"); 
     }); 
    }); 
    } 
    else 
    { 
    cell.imageView.image = [imagesDictionary objectForKey:row]; 
    NSLog(@"retriving from dictioary"); 
    } 
    return cell; 
} 
+0

Комментарии не предназначены для расширенного обсуждения; этот разговор был [перемещен в чат] (http://chat.stackoverflow.com/rooms/66655/discussion-on-answer-by-shan-how-to-set-image-path-coming-from-server- в-uitable). – Taryn

2

Dont использовать imageWithData: для настройки изображения. Это синхронно и заставит ваше приложение работать медленно.

Вместо этого использования SDWebImage

Вам просто нужно сделать следующие вещи: папка SDWebImage

  1. Dump в свой проект.

  2. Импорт UIImageView+WebCache.h.

  3. Установить изображение с помощью: sd_setImageWithURL:

ИЛИ

от GCD (Grand Central Dispatch) and sending asynchronous requests. Код скопирован с HERE.

Первый реализовывать следующий способ.

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock 
{ 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
           if (!error) 
           { 
            UIImage *image = [[UIImage alloc] initWithData:data]; 
            completionBlock(YES,image); 
           } else{ 
            completionBlock(NO,nil); 
           } 
          }]; 
} 

, а затем в вашем cellForRowAtIndexPath

[self downloadImageWithURL:your_url completionBlock:^(BOOL succeeded, UIImage *image) { 
      if (succeeded) { 
       // change the image in the cell 
       cell.imageView.image = image; 


      } 
     }]; 
+0

любой другой вариант кроме этого? –

+0

[AFNetworking] (https://github.com/AFNetworking/AFNetworking), но я бы предложил SDWebImage. Он широко используется n легко понять. – Rumin

+0

любой другой встроенный опцион ?? –

1

Прежде всего вы звоните dataWithContentsOfURL: функция, которая сделает приложение не реагирует, потому что вы вызываете его на главном потоке. Для того, чтобы сделать его отзывчивым вам нужно создать пользовательскую ячейку YourCell и объявить метод в YourCell.h

@interface YourCell : UITableViewCell 
{ 
    UIImage *_cImage; 
} 

- (void)downloadImageFromURL:(NSURL *)imageUrl; 
@end 

Сейчас в YourCell.m вам нужно сделать так:

- (void)downloadImageFromURL:(NSURL *)imageUrl 
{ 
    if (_cImage != nil) 
    { 
     self.imageView.image = _cImage; 
    } 
    else 
    { 
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     _cImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]]; 

     dispatch_sync(dispatch_get_main_queue(), ^{ 
       self.imageView.image = _cImage; 
      }); 
     }); 
    } 
} 

Теперь из cellForRowAtIndexPath: вам просто нужно вызвать функцию downloadImageFromURL: функцию YourCell и передать ему imageUrl и ее ответственность за загрузку и отображение изображения.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier= @"YourCell"; 
    YourCell *cell = (YourCell *)[self.activitiesTableView_ dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[[NSBundle mainBundle] loadNibNamed:@"YourCell" owner:self options:nil] objectAtIndex:0]; 
    } 

    // Set your UILabels as before..... 

    NSString *imagePath=[[self.inboxmessagesarray objectAtIndex:indexPath.row] objectForKey:@"offerPhoto"]; 
    [cell downloadImageFromURL:[NSURL URLWithString:imagePath]]; 

    return cell;   
} 

Дайте мне знать, если возникнут какие-либо вопросы.

+0

вы, пожалуйста, укажите ячейку для метода индексной строки строки? –

+0

Функция @MishalAwan добавлена ​​в сообщение. –

+0

@MishalAwan голосовать, если вы найдете сообщение полезным. Спасибо –

0
UIImageView *img1 = (UIImageView *)[cell viewWithTag:104]; 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      img1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; 
     }); 
    }); 

Отправить async-запросы на изображения. Это не будет блокировать ваш пользовательский интерфейс, пока изображение не будет загружено.

+0

Какова цель этого? –

+0

Вышеприведенный код может использоваться для отправки асинхронных запросов в отличие от используемого вами кода, который отправляет запросы синхронизации. Отправка запросов на синхронизацию полностью блокирует пользовательский интерфейс, пока не будет загружено все изображение. Скажем, если ваш интернет медленный, тогда весь ui загружается, за исключением изображений, если вы используете запрос Async. –

+0

и что такое fromimage.image it id, дающий ошибку в моей стороне? –

Смежные вопросы