Objective c 是否将UITextView中的数据保存到文件?

Objective c 是否将UITextView中的数据保存到文件?,objective-c,Objective C,我正在使用一个SSH库,我的应用程序中有一个部分,您可以通过在UITextView中编写HTML文档来创建它,然后我希望能够将它上载到服务器。在上传到服务器之前,我必须将文本文件暂时保存为“.html”格式,这一点让我很为难。我知道我可以从文本视图中获取所有文本,但如何为其提供文件扩展名? 谢谢 我参考了SO线程以了解如何将其保存到文件中,但保存后如何访问该文件 NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocu

我正在使用一个SSH库,我的应用程序中有一个部分,您可以通过在UITextView中编写HTML文档来创建它,然后我希望能够将它上载到服务器。在上传到服务器之前,我必须将文本文件暂时保存为“.html”格式,这一点让我很为难。我知道我可以从文本视图中获取所有文本,但如何为其提供文件扩展名? 谢谢

我参考了SO线程以了解如何将其保存到文件中,但保存后如何访问该文件

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"test.html"];


htmlCode = self.htmlText.text;
NSError* error = nil;
[htmlCode writeToFile:documentHTMLPath atomically:YES encoding:NSASCIIStringEncoding error:&error];
NSStringEncoding encoding;
NSString* fileToUpload = [NSString stringWithContentsOfFile:documentHTMLPath usedEncoding:&encoding error:&error];

如果您有要写入的文件的URL,则可以使用相同的URL再次访问该文件

编辑以添加

NSURL *documentDirectoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

NSURL *documentURL = [documentDirectoryURL URLByAppendingPathComponent:@"test.html"];


htmlCode = self.htmlText.text;

NSError* error;

if (![htmlCode writeToURL:documentURL atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"Couldn't save file because: %@", error);
}

NSString* fileToUpload = [NSString stringWithContentsOfURL:documentURL encoding:NSUTF8StringEncoding error:&error];

if (!fileToUpload) {
    NSLog(@"Couldn't read file because: %@", error);
}
  • 现在最好使用URL而不是字符串路径

  • 尽可能使用UTF8

  • 当NSError参数对您可用时,请始终使用该参数。当您想知道为什么不能保存或读取文件时,即使是我在这里展示的基本错误处理也比没有要好

  • 是的,您保存到的URL与您从中读取的URL相同。在这种情况下,它是
    documentURL


谢谢!如果我使用我在上述代码中添加的内容,那么路径将是什么字符串?documentTEXTPath?非常感谢!这太棒了。