How to save a locally loaded HTML file in UIWebvie

2019-05-23 08:24发布

I am writing a rich text editor using UIWebView. To do this, I used a template file for a starter.

Then when user finishes editing but has not published yet, I would like to save the current content into a back-up html file in case app corrupts.

How do I do that?

2条回答
霸刀☆藐视天下
2楼-- · 2019-05-23 08:54

Thanks @Rahui Vyas and @Josh Caswell .. After a little research of my own. I have found the easiest way to save the locally loaded html file or any html loaded on UIWebview.

long words short, here is the code:

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

Hope the laters may find this useful!

查看更多
SAY GOODBYE
3楼-- · 2019-05-23 09:01

Here you go... buddy

    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");

Complete Tutorial Below

Working With File I/O in objective-c

查看更多
登录 后发表回答