ios - 如何访问目录

标签 ios objective-c filesystems

我想将图像保存在文件夹中。我已经有代码了。下载并保存图像,但我想知道如何找到 ma 文件夹的路径! 我在 xcode 中创建了一个目录,但图像找不到它并且其中没有图像。 所以,我想将图像保存在“img_bkgrd”文件夹中。 enter image description here

[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", imageName]] options:NSAtomicWrite error:nil];

要使用图片我用这个方法:

-(UIImage *) loadImage:(NSString *)fileName inDirectory:(NSString *)directoryPath{
 UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", directoryPath, fileName]];
 return result;

你能把正确的路径发给我吗? 谢谢

最佳答案

你不能在那里保存图像。首先,这实际上不是一个文件夹。它被称为。它是应用程序包的一部分,是只读的。您需要将数据保存到 Documents 目录中。类似的东西:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *imageFolderPath = [documentsDirectory stringByAppendingPathComponent:@"/img_bckr"];

if (![[NSFileManager defaultManager] fileExistsAtPath:imageFolderPath])
     [[NSFileManager defaultManager] createDirectoryAtPath:imageFolderPath withIntermediateDirectories:NO attributes:nil error:&error];

NSString* imagePath = [imageFolderPath stringByAppendingPathComponent:@"MyImage"];

[UIImageJPEGRepresentation(image, 1.0) writeToFile:imagePath options:NSAtomicWrite error:nil];

您可以将 imagePath 存储在某处或稍后根据文件名构建它,然后简单地:

UIImage* img = [UIImage imageWithContentsOfFile:imagePath];

关于ios - 如何访问目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49782334/

相关文章:

ios - 尝试启动 MapKit 位置更新而不提示在 ios 9 中使用 objective-c 进行位置授权

ios - 解析产品链接返回 null

c++ - 获取被删除文件名的API

c - 如何让 NFS 支持 posix_fallocate?

ios - UITapGestureRecognizer 在 UITextView 中触发一次

ios - 使用 CFStreamCreatePairWithSocketToHost 建立 IPV6 套接字连接

ios - "The user is blocked from live streaming."(域=com.google.GTLRErrorObjectDomain代码=403)

node.js - 在 Node.js 中事务性地写入文件

ios - 仅在 xcode 中启动 iPhone 目标,而不启动 OSwatch 目标,当两者都存在于项目中时

ios - 如何正确确保 32 位和 64 位兼容性?