[英]How can I read documents in my app's Document directory from other iOS apps?
[英]Why can't I save files to my iOS apps /Documents directory?
我正在编写一个可以访问iOS根系统的应用程序,该用户应该能够将文件保存到他的文档目录中。 我正在使用此代码将文件保存到文档目录。
对于文字:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, [self.filePath lastPathComponent]]
atomically:YES
encoding:NSUTF8StringEncoding error:nil];
对于其他文件:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory,[self.filePath lastPathComponent]]
atomically:YES];
我的问题是我可以保存.txt文件,但不能保存其他文件,例如,如果使用保存文本方法保存.plist文件,则联系人将被文件的目录路径替换。 当我保存图片或任何其他文件时,它是不可读的。 有没有保存文件而不破坏文件的好方法?
您正在调用[self.filePath writeToFile:]
,从而将filePath
变量的内容写入文件。
您应该执行以下操作:
[contents writeToFile:...]
这里有一个保存图像的例子:
假设您将图像的内容放入NSData对象中:
NSData *pngData = UIImagePNGRepresentation(image);
然后将其写入文件:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
请查看以下问题以获取更详细的解释:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.