使用ASIhttprequest下载图像并从本地保存的文件显示图像

时间:2012-07-03 13:02:42

标签: iphone ios ios4 asihttprequest

在我的应用程序中完成购买时,我将图像从服务器下载到应用程序。

我可以从网上下载图像,然后使用asihttprequest在iPhone内写。

我在iphone的模拟器文件目录里面检查过,下载的文件存在。

我是怎么做的,我在点击按钮时在桌面视图中放置了一个uibutton,它开始下载并在uitableviewcell中显示。

直到这是好的。当回到同一个uitableview时,图像不会显示。只是空。当我再次点击uibutton时,它开始从网上下载。

我不确定如何显示本地保存的图像?以及如何显示下载并写入应用程序的图像,如果图像在应用程序内不可用,则需要从服务器开始下载。

请指导我

请是我的代码

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath 
//-------------------------------------------------------------------------------
{
    int tablePadding = 40;
    int tableWidth = [self.tblPoemTypes frame].size.width;
    if (tableWidth > 480) { 
        tablePadding = 110;
    }


    static NSString *CellIdentifier = @"PoemTypeCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero]autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;



            // Only load cached images; defer new downloads until scrolling ends
           /* if (!psTypeTags.image)
            {
                cellImageView.image = [UIImage imageNamed:@"no-image-available.jpg"]; 
                [cell.contentView addSubview:cellImageView];

                [self startIconDownload:psTypeTags forIndexPath:indexPath];
            }
            else
            {
                NSLog(@"YES Image *****************");
                cellImageView.image = psTypeTags.image;
                [cell.contentView addSubview:cellImageView];
            }*/

            //----added by re

            if([indexPath row]==0)
            {

                goButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                [goButton setTitle:@"Go" forState:UIControlStateNormal];
                [goButton sizeToFit];
                [goButton setFrame:CGRectMake(220,30,50,30)];

                [goButton addTarget:self action:@selector(fetchThreeImages1:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:goButton];

                imageView1 = [[[UIImageView alloc] initWithFrame:CGRectZero] autorelease];
                [imageView1 setBackgroundColor:[UIColor grayColor]];


                [imageView1 setImage:[array objectAtIndex:0]];
                [cell addSubview:imageView1];

                imageProgressIndicator1 = [[[UIProgressView alloc] initWithFrame:CGRectZero] autorelease];
                [cell addSubview:imageProgressIndicator1];  

            }

        NSUInteger imageWidth = (tableWidth-tablePadding-20)/3;
        NSUInteger imageHeight = 35;

        [imageView1 setFrame:CGRectMake(tablePadding/2,20,imageWidth,imageHeight)];

        [imageProgressIndicator1 setFrame:CGRectMake(120,40,imageWidth,20)];


            //-----------------

              }

    return cell;
}
- (void)fetchThreeImages1:(id)sender
{
    [imageView1 setImage:nil];

    if (!networkQueue) {
        networkQueue = [[ASINetworkQueue alloc] init];  
    }
    failed = NO;
    [networkQueue reset];
    [networkQueue setRequestDidFinishSelector:@selector(requestForDownloadOfFileFinished:)];
    [networkQueue setRequestDidFailSelector:@selector(requestForDownloadOfFileFailed:)];



    [networkQueue setShowAccurateProgress:YES];
    [networkQueue setDelegate:self];
    self.request=nil;

    NSURL *url;

    NSString *urlString=@"http://cdn.visual-blast.com/wp-content/uploads/2012/03/1700-royalty-free-stock-images-48x48.jpg";
    url = [NSURL URLWithString:urlString];
    request = [ASIHTTPRequest requestWithURL:url];


    [request setDownloadProgressDelegate:imageProgressIndicator1];
    [request setUserInfo:[NSDictionary dictionaryWithObject:@"request1" forKey:@"name"]];
    [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"1.png"]];
    [request setShouldContinueWhenAppEntersBackground:YES];
    [request setDelegate:self];
    [request setDidReceiveDataSelector:@selector(request:didReceiveBytes:)]; 
    [request setShowAccurateProgress:YES];

    [networkQueue addOperation:request];


    [networkQueue go];

}
- (void)requestForDownloadOfFileFinished:(ASIHTTPRequest *)request1
{

    NSLog(@"req finish.........");
    NSLog(@"Content will be %llu bytes in size",[request1 contentLength]); 

    goButton.hidden=YES;
    [imageProgressIndicator1 removeFromSuperview];
    UIImage *img = [UIImage imageWithContentsOfFile:[request1 downloadDestinationPath]];
    array=[[[NSMutableArray alloc]init]autorelease];
    [array addObject:img];
    image = [[UIImage alloc ]initWithData:[request1 responseData]];


    NSString *receivedString = [request1 responseString];
    NSLog(@"received string %@",receivedString);
    NSData *responseData = [request1 responseData];

    NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    NSLog(@"Server response:%@", response);

    NSLog(@"response data %@",[request1 responseData]);
    NSLog(@"download destination path %@",[request downloadDestinationPath]);
    NSLog(@"download destination path1 %@",[request1 downloadDestinationPath]);
    NSLog(@"image %@",img);
    NSLog(@"image1 %@",image);
    if (img) {
        [imageView1 setImage:img];
    }
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"Download" message:@"Download Completed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [alertView show];
    //completed=true;
    NSLog(@"mutablearray count %@",[array objectAtIndex:0]);

    //[self.tblPoemTypes reloadData];

}

- (void)requestForDownloadOfFileFailed:(ASIHTTPRequest *)request1
{
    if (!failed) {
        if ([[request1 error] domain] != NetworkRequestErrorDomain || [[request1 error] code] != ASIRequestCancelledErrorType) {
            UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"Download failed" message:@"Failed to download images" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
            [alertView show];
        }
        failed = YES;

    }

}

2 个答案:

答案 0 :(得分:1)

下载图像后,您必须将图像保存在文档目录中。因此,当您启动tableview时,首先检查文档中是否存在该图像,如果存在则直接将图像显示为:

编辑:

 - (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

-(void)loadimage{
    NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"your image-name"];
    UIImageView *myimage=[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)];
    myimage.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];    
    [self.view addSubView:myimage];
    [myimage release];
}

如果不存在则下载。

答案 1 :(得分:0)

看看这个项目: https://github.com/rs/SDWebImage/