2012-07-04 34 views
0

下面的代码并不显示这是从网上下载并写进我的申请文件目录中的图片。 我的iPhone的模拟器文件目录中已经检查,所下载的文件是存在的。 但不显示图像。图像没有被显示:NSData的dataWithContentsOfFile

当试图添加使用UIImage *imgBack = [UIImage imageNamed:@"btn-back.png"];一个资源形象,UIImageView的显示image.bu这是从网上下载并存储内部应用程序目录不显示图像的图像。

请让我知道,谢谢

NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:theFileName]; 
NSLog(@"%@ workSpacePath ",workSpacePath); 
if (workSpacePath){ 

     //-------------- 
     UIImage *imgBack = [UIImage imageNamed:@"btn-back.png"]; 
     imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)] autorelease]; 
     [imageView1 setBackgroundColor:[UIColor grayColor]]; 

     imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]]; 
     [cell addSubview:imageView1]; 
} 
+0

你检查workSpacePath?它是否显示图像的正确路径? –

+0

希望这个链接会帮助你,http://stackoverflow.com/questions/2037432/saving-image-to-documents-directory-and-retrieving-for-email-attachment –

+0

是的,它显示了正确的路径 – user198725878

回答

1

试试这个,这是完美的工作对我来说:

- (void)viewDidLoad 
{ 
  [super viewDidLoad]; 

    NSURL *url1 = [NSURL URLWithString:@"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"]; 
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"]; 

    NSData *imageData = UIImagePNGRepresentation(image); 
    [imageData writeToFile:savedImagePath atomically:NO]; 

    NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory1 = [paths1 objectAtIndex:0]; 
    NSString *workSpacePath = [documentsDirectory1 stringByAppendingPathComponent:@"savedImage.png"]; 
    NSLog(@"%@ workSpacePath ",workSpacePath); 

if (workSpacePath) 
    { 
     imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(20,20,20,20)]; 
     [imageView1 setBackgroundColor:[UIColor grayColor]]; 

     imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]]; 
     [self.view addSubview:imageView1]; 

    } 
} 
1

而不是第一个文件转换为NSData,您可以使用

[UIImage imageWithContentsOfFile:filePath]

直接加载image与给定的路径。

+0

+1完美优雅的解决方案:D –