首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSFileManager未保存

NSFileManager未保存
EN

Stack Overflow用户
提问于 2012-09-03 11:46:31
回答 1查看 858关注 0票数 0

我一直在尝试使用NSFileManager将图片缓存到沙盒应用程序的缓存目录中。不幸的是,我的代码似乎不能工作。

代码语言:javascript
复制
- (BOOL)saveImageToCacheFolder
{
    NSFileManager *filemgr = [NSFileManager defaultManager];
    NSString *cachePath = [[[filemgr URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject] absoluteString];
    NSString *fullpath = [cachePath stringByAppendingPathComponent:@"test.jpg"];
    NSURL *imageURL = [FlickrFetcher urlForPhoto:self.photoData format:FlickrPhotoFormatLarge];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

    BOOL success = false;
    if (imageData != nil) {
        success = [imageData writeToURL:[NSURL URLWithString:fullpath] atomically:true];
        if (!success) NSLog(@"Did Not Managed to save the image");
    }
    return success;
}

这就是我想要做的。首先,获取默认的NSFileManager。其次,获取我的应用程序缓存目录的相对路径。第三,附加我的文件名(这里我现在只写了test )。第四,将我的图像转换为NSData。第四,将NSData对象写入指定的路径。

edit:添加if语句,用于检查imageData是否为空

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-03 12:07:38

试试这个:

代码语言:javascript
复制
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath    = [myPathList  objectAtIndex:0];
NSString *fullpath = [cachePath stringByAppendingPathComponent:@"test.jpg"];

NSURL *imageURL = [FlickrFetcher urlForPhoto:self.photoData format:FlickrPhotoFormatLarge];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

if (imageData != nil) {
    success = [imageData writeToURL:[NSURL fileURLWithPath:fullpath] atomically:YES];
    if (!success) NSLog(@"Did Not Managed to save the image");
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12241745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档