2017-02-07 3 views
0

Я новичок в прошивке и я перед проблемой относительно показать изображение в изображении Вида с вебом-Service.I Я использую код, как этогоПочему изображение не отображается в cellforRowAtIndexPath в объективных C

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *[email protected]"STI"; 
    NewsTableViewCell *cell = (NewsTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI]; 
    if (cell == nil) 
    { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"NewsTableViewCell" owner:self options:nil]; 
     cell = [nib objectAtIndex:0]; 
     cell.accessoryType=UITableViewCellAccessoryNone; 
    } 

    NSString *strImgURLAsString = [NewsImageArray objectAtIndex:indexPath.row]; 
    [strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSURL *imgURL = [NSURL URLWithString:strImgURLAsString]; 
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
     if (!connectionError) { 
      img = [[UIImage alloc] initWithData:data]; 
      if (img==nil) { 
       // img=[UIImage imageNamed:@"userimage.png"]; 
      } 
      cell.newsimage.image=img; 

      // pass the img to your imageview 
     }else{ 
      NSLog(@"%@",connectionError); 
     } 
    }]; 

    cell.Headlbl.text=[NSString stringWithFormat:@"%@",[headarray objectAtIndex:indexPath.row]]; 

    NSString *aux = [shortnamearray objectAtIndex:indexPath.row]; 
    NSString * htmlString = @"<html><body>"; 
    NSString *[email protected]"</body></html>"; 
    NSString * NewString=[NSString stringWithFormat:@"%@%@%@",htmlString,aux,htmlString2]; 

    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[NewString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 

    cell.bodylbl.attributedText=attrStr; 
    cell.bodylbl.textAlignment=NSTextAlignmentCenter; 
    cell.bodylbl.textColor=[UIColor whiteColor]; 
    [cell.bodylbl setFont:[UIFont fontWithName:@"Arial" size:16]]; 

    cell.backgroundColor = cell.contentView.backgroundColor; 


    // cell.bodylbl.text=[NSString stringWithFormat:@"%@",[shortnamearray objectAtIndex:indexPath.row]]; 
// cell.randrid.text=[NSString stringWithFormat:@"%@",[idarray objectAtIndex:indexPath.row]]; 
    return cell; 

} 

Image Path - http://qaec.teams.in.net/UploadedFiles/Tommy Schaefer, его роль в убийстве, за которое он отбывает 18 year.png

http://qaec.teams.in.net/UploadedFiles/Tommy%20Schaefer,%20of%20his%20role%20in%20the%20slaying,%20for%20which%20he%20is%20serving%2018%20year.png 

enter image description here когда изображение не содержит каких-либо пробелов он показывает изображение Но когда изображение содержит какой-либо разрыв не шо w image.Как решить эту проблему. Спасибо в Advance!

+0

комплект Try изображение в главном потоке: 'dispatch_async (dispatch_get_main_queue()^{ cell.newsimage.image = IMG; });' – nynohu

+0

добавьте экран изображение, которое не отображается – iOS

+0

@nynohu Не работа. – Muju

ответ

1

Там нет необходимости использовать какие-либо другие библиотеки и т.д. Ваш код ошибки на этой линии:

[strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

Посмотрите на это, что он делает? Ничего. Вы должны передать переменную strImgURLAsString на это, то он должен работать:

strImgURLAsString = [strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
+0

Нет, не работает. Еще не показано изображение. – Muju

+0

Thats weird Я только что проверил в xcode, и он работает. Изображение большое, поэтому подождите некоторое время. – GeneCode

+0

Не знаете, почему код работает в моем xcode и не работает в вашем. Это странно, потому что я копирую ваш код и изменяю только «strImgURLAsString =», и он работает. – GeneCode

0

Использование так:

[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
     if (!connectionError) { 

      dispatch_async(dispatch_get_main_queue(), ^{ 
      img = [[UIImage alloc] initWithData:data]; 
      if (img==nil) { 
       // img=[UIImage imageNamed:@"userimage.png"]; 
      } 
      cell.newsimage.image=img; 

      // pass the img to your imageview 
      }); 
     }else{ 
      NSLog(@"%@",connectionError); 
     } 
    }]; 
+0

Нет, не работает. Не отображается изображение. – Muju

0

Я знаю, что это хорошая идея, чтобы загрузить URL изображения в ImageView, как, как вы написали для лучшего понимания процесса. Но важно следить за кешем. Для лучшей производительности я рекомендую вам использовать очень хорошую библиотеку под названием SDWebImage. Это помогает вам быстрее загружать изображения с помощью механизма кэширования. Попробуйте это. С этой библиотекой это очень просто.

[imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] 
     placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; 

Вот еще один. Если вы используете AFNetworking в своем приложении, используйте ниже код для этого.

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; 
requestOperation.responseSerializer = [AFImageResponseSerializer serializer]; 
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Response: %@", responseObject); 
    _imageView.image = responseObject; 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Image error: %@", error); 
}]; 
[requestOperation start]; 
1

Для лучшей производительности вы можете попробовать эту библиотеку под названием SDWebImage.

[imageView sd_setImageWithURL: [NSURL URLWithString: @ "http://qaec.teams.in.net/UploadedFiles/Tommy%20Schaefer,%20of%20his%20role%20in%20the%20slaying,%20for%20which%20he%20is%20serving%2018%20year.png"] placeholderImage: [UIImage imageNamed: @ "placeholder.png"]];

Также Вы должны убедиться, что вы написали это в вашем файле Plist enter image description here

3

Вы можете использовать следующий метод в классе UITableViewCell. В вашем случае добавьте код в NewsTableViewCell.m. Когда ячейка создана, вызывается метод времени drowRect. Таким образом, в этом методе вам нужно установить свойство setClipsToBounds изображения, для которого вы устанавливаете изображение в YES. Это решит вашу проблему.

-(void)drawRect:(CGRect)rect 
{ 
    [super drawRect:rect]; 
    self.profilePicImgView.layer.cornerRadius=self.profilePicImgView.frame.size.width/2; 
    [self.profilePicImgView setClipsToBounds:YES]; 
    [self.profilePicImgView layoutIfNeeded]; 
    [self.profilePicImgView setNeedsDisplay]; 
}