1

我正在编写一个可以访问 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 文件,则联系人将替换为文件的目录路径。当我保存图片或任何其他文件时,它不可读。有没有一种很好的方法来保存文件而不破坏它们?

4

2 回答 2

7

您正在调用[self.filePath writeToFile:],从而将filePath变量的内容写入文件。

您应该执行以下操作:

[contents writeToFile:...]
于 2013-08-28T14:02:10.447 回答
4

这里有一个保存图像的示例:

假设您将图像的内容放入 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

查看这些问题以获得更详细的解释:

在 iOS 上编写文件

从 iOS 上的 UIView 将图像保存到应用程序文档文件夹

于 2013-08-28T14:03:07.533 回答