以编程方式下载html页面 - Objective C / Xcode

时间:2012-06-18 09:06:43

标签: iphone objective-c ios xcode ipad

我在iPad的detailView应用SplitView底部有一个名为“下载页面”的按钮。我想点击上述按钮下载相应的html页面,即我需要为该按钮添加“Ctrl + S”的功能,以便我可以下载并保存页面。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

你应该这样做:

//Download data from URL
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"yourstringURL"]];
//use this data to write to any path as documentdirectory path + filename.html
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//create file path
NSString *htmlFilePath = [documentsDirectory stringByAppendingPathComponent:@"file.html"];
//write at file path
BOOL isSucess = [data writeToFile:htmlFilePath atomically:YES];
if (isSucess)
    NSLog(@"written");
else
    NSLog(@"not written");

您可以htmlFilePathhtml

中检索document directory文件

答案 1 :(得分:2)

您可以获取NSString中的所有html内容,然后保存它,就像这样

NSString *allHtml = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
[allHtml writeToFile:@"YourFilePath" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

这会将所有HTML保存到您定义的路径