下载后加载资源(ios)

时间:2015-02-19 06:38:53

标签: ios objective-c iphone

我正在从服务器下载资源并使用以下代码成功将其写入文档目录

NSString *fileName = [[[NSURL URLWithString:url] path] lastPathComponent];

NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];

NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSLog(@"File written");

NSError *writeError = nil;

[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
    NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError );
    return;
}
NSLog(@"%@",fileURL);

现在我想访问这些文件以使用它。我试过这段代码

-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{

   UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];
   return result;
}

现在使用的方法是这样的:

UIImage *imageFromWeb = [self loadImage:@"metaioman" ofType:@"png" inDirectory:folder];

_imgview.image=imageFromWeb;

但没有运气......请帮忙

谢谢

1 个答案:

答案 0 :(得分:0)

首先使用NSFileManager检查文件是否存在。

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *pathForFile = [NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]

UIImage * result = nil;
if ([fileManager fileExistsAtPath:pathForFile]){ 
    //file exists
    result = [UIImage imageWithContentsOfFile:pathForFile];
}
else
{
   //file doesnot exists or wrong filename.
}
return result;

参考http://beageek.biz/save-and-load-uiimage-in-documents-directory-on-iphone-xcode-ios/