图像缓存不起作用?

时间:2013-12-02 07:42:36

标签: ios iphone

大家好我是ios开发的新手,我正在进行JSON解析并获取数据并使用ImageView和Title在UITableView上显示,一切都很好但是图像缓存在我的代码中是一个问题,我的图像正在加载但是它花了很多时间,当我滚动我的tableview时,它再次获取单元格所需的图像。任何人都可以在我现在的代码中提出缓存解决方案我已经多次搜索但无法弄清楚这一点。这真有帮助,如果有人请建议我类似的例子或协助我这个。提前致谢。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSString *post =[[NSString alloc]init];
    NSLog(@"PostData: %@",post);

    NSURL *url=[NSURL URLWithString:@"http://www.xyz.com/consumer_id=1”];    
    NSData *postData = [ post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

    NSError *error = [[NSError alloc] init];
    NSHTTPURLResponse *response = nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSLog(@"Response code: %d", [response statusCode]);
    if ([response statusCode] >=200 && [response statusCode] <300)
    {
        NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
        NSLog(@"Response ==> %@", responseData);

        SBJsonParser *jsonParser = [SBJsonParser new];
        NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
        NSLog(@"%@",jsonData);

        NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
        NSLog(@"%d",success);
        data = [jsonData objectForKey:@"data"];


    }
}

#pragma mark - 表视图数据源

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [data count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";

    SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    NSDictionary *myNames = [data objectAtIndex:[indexPath row]];
    NSLog(@"%@",myNames);

    [cell.nameLabel setText:[myNames objectForKey:@"name"]];

    NSString *imageURL = [myNames objectForKey:@"image"];

    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];

    UIImage *imageIcon = [UIImage imageNamed:@"license.png"];

    NSLog(@"ImageIcon %@",imageIcon);

    [cell.thumbnailImageView setImage:imageIcon];

    cell.thumbnailImageView.image = [UIImage imageWithData:imageData];

    return cell;
}

2 个答案:

答案 0 :(得分:0)

尝试使用设置占位符图片异步显示图像,因为您的图像来自网络服务。

dispatch_async(dispatch_get_main_queue(),^{

[image setImageWithURL:your url placeholderImage:[UIImage imageNamed:@""]];

});

here尝试此SDWebImage。

答案 1 :(得分:0)

  -(void)viewDidAppear:(BOOL)animated
 {


NSMutableArray *arrtInvitationList=[[NSMutableArray alloc]init];

NSString *  urlString=[NSString stringWithFormat:@"Your Url"];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     NSError *error1;
     NSDictionary *res=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];

 // you are getting dictinary here according ur dictinary parse the data .......

     if ([[res valueForKey:@"status"]isEqualToString:@"true"]) {
         NSLog(@"%d",[[res valueForKey:@"result"] count]);

         for (int i=0; i<[[res valueForKey:@"result"] count]; i++)
         {
             NSMutableDictionary *dict  = [[NSMutableDictionary alloc]init];
             //[dict setObject:[[[[res valueForKey:@"player1"] objectAtIndex:i] valueForKey:@"result"] objectAtIndex:i] ];

             [arrtInvitationList addObject:dict];
             [tblInvite reloadData];
         }
         [HUD hide:YES];

     }else
     {
         [HUD hide:YES];

     }

 }];



}


  //After that add this array your table view there also when u adding image add asynchronous method

      NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
//
   [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         UIImage *imagemain=[UIImage imageWithData:data];
                  CGSize size=imagemain.size;
         UIImage *compimage=[self resizeImage:imagemain resizeSize:CGSizeMake(45,45)];
//
         Cell.imgProfile.image=compimage;
//         //         CGSize size1=compimage.size;
//     }];


  this adding image to cell and resize the image also........

  -(UIImage *) resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size
  {
CGFloat actualHeight = orginalImage.size.height;
CGFloat actualWidth = orginalImage.size.width;
//  if(actualWidth <= size.width && actualHeight<=size.height)
//  {
//      return orginalImage;
//  }
float oldRatio = actualWidth/actualHeight;
float newRatio = size.width/size.height;
if(oldRatio < newRatio)
{
    oldRatio = size.height/actualHeight;
    actualWidth = oldRatio * actualWidth;
    actualHeight = size.height;
}
else
{
    oldRatio = size.width/actualWidth;
    actualHeight = oldRatio * actualHeight;
    actualWidth = size.width;
}

CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
UIGraphicsBeginImageContext(rect.size);
[orginalImage drawInRect:rect];
orginalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return orginalImage;
    }