2013-05-14 75 views
2

我正在使用UIWebView編寫一個富文本編輯器。爲此,我使用了一個模板文件作爲初學者。如何在UIWebview中保存本地加載的HTML文件

然後當用戶完成編輯但尚未發佈時,我想將當前內容保存到備份html文件中,以防應用程序損壞。

我該怎麼做?

+0

你需要閱讀一些文件I/O和NSFileManager :) – 2013-05-14 04:32:51

回答

1

在這裏你去...哥們

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

完全教程下面

Working With File I/O in objective-c

+0

@JoshCaswell謝謝先生 – 2013-05-14 05:02:33

0

感謝@Rahui維亞斯和@Josh卡斯威爾..我自己的一些研究之後。我找到了最簡單的方法來保存本地加載的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]; 

望laters可能會有所幫助!

相關問題