0

I'm working with an SSH library and I have a part in my application where you can create an HTML document by writing it in UITextView, then I want to be able to upload it to the server. I'm stuck on the part where I have to save the text file in a ".html" format temporarily, before uploading to a server. I know I can get all the text from the text view, but how do I give it a filename extension? Thanks!

I referred to this SO thread to learn about saving it to file, but how do I access the file once it's saved?

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];
4

1 回答 1

1

如果您有正在写入的文件的 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

于 2013-06-05T01:35:48.793 回答