user425243
user425243

Reputation:

Programmatically download html page - Objective C/Xcode

I have a button called "Download page" at the bottom of my detailView of SplitView app in iPad. I want to download the corresponding html page on the click of the aforementioned button i.e. I need to add the functionality of the "Ctrl+S" for that button so that I could download and save the page. How can I do that ?

Upvotes: 2

Views: 2440

Answers (2)

Paresh Navadiya
Paresh Navadiya

Reputation: 38249

You should do this:

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

You can same htmlFilePath to retrieve html file from document directory

Upvotes: 3

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

You can get all the html content inside an NSString and then save it, like so

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

This will save all the HTML to the path you define

Upvotes: 2

Related Questions