【发布时间】:2013-05-14 04:25:43
【问题描述】:
我正在使用 UIWebView 编写富文本编辑器。为此,我使用了一个模板文件作为初学者。
然后当用户完成编辑但尚未发布时,我想将当前内容保存到备份 html 文件中,以防应用损坏。
我该怎么做?
【问题讨论】:
-
你需要阅读一些文件 I/O 和 NSFileManager :)
标签: objective-c cocoa-touch uiwebview
我正在使用 UIWebView 编写富文本编辑器。为此,我使用了一个模板文件作为初学者。
然后当用户完成编辑但尚未发布时,我想将当前内容保存到备份 html 文件中,以防应用损坏。
我该怎么做?
【问题讨论】:
标签: objective-c cocoa-touch uiwebview
给你……伙计
NSFileHandle *file;
NSMutableData *data;
const char *bytestring = "black dog";//In your case html string here
data = [NSMutableData dataWithBytes:bytestring length:strlen(bytestring)];
NSString *path = //Path to your html file
if ([filemgr fileExistsAtPath:path] == YES){
NSLog (@"File exists");
file = [NSFileHandle fileHandleForUpdatingAtPath:path];
if (file == nil)
NSLog(@"Failed to open file");
[file writeData: data];
[file closeFile];
}
else
NSLog (@"File not found");
下面的完整教程
【讨论】:
感谢@Rahui Vyas 和@Josh Caswell .. 经过我自己的一些研究。我找到了保存本地加载的 html 文件或 UIWebview 上加载的任何 html 的最简单方法。
长话短说,代码如下:
//load the file path to save
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savePath = [documentsDirectory stringByAppendingPathComponent:@"backup.html"];
//get the html code from the webview
NSString *jsToGetHTMLSource = @"document.documentElement.outerHTML";
NSString *html = [_changWeiBo stringByEvaluatingJavaScriptFromString:
jsToGetHTMLSource];
//save the file
NSError* error = nil;
[html writeToFile:savePath atomically:YES encoding:NSASCIIStringEncoding error:&error];
希望后人会觉得这很有用!
【讨论】: