我最终像这样从网络加载图像:
- (void) cacheImage: (NSURL *) ImageURL : (NSString *)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dir = [paths objectAtIndex: 0];
NSString *file = [docDir stringByAppendingPathComponent: imageName];
if(![[NSFileManager defaultManager] fileExistsAtPath: file])
{
NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];
UIImage *image = [[UIImage alloc] initWithData: data];
[UIImageJPEGRepresentation(image, 100) writeToFile: docFile atomically: YES];
}
}
通过以下方式缓存并返回文件 url:
- (NSString *) getCachedImage : (NSString *)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* cachedPath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSString *path;
if([[NSFileManager defaultManager] fileExistsAtPath: cachedPath])
{
path = cachedPath;
}
return path;
}
并通过加载文件
NSString *cached = [self getCachedImage:@"cacheKey"];
self.skyboxCubemap = [GLKTextureLoader cubeMapWithContentsOfFile:cached options:options error:&error];