Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS download and save HTML file

I am trying to download a webpage (html) then display the local html that has been download in a UIWebView.

This is what I have tried -

NSString *stringURL = @"url to file";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
    NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];  

    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"index.html"];
    [urlData writeToFile:filePath atomically:YES];
}

    //Load the request in the UIWebView.
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];        // Do any additional setup after loading the view from its nib.

But this gives a 'SIGABRT' error.

Not too sure what I have done wrong?

Any help would be appreciated. Thanks!

like image 366
AveragePro Avatar asked Apr 09 '11 18:04

AveragePro


People also ask

How do I save a HTML file?

Choose File > Save As and choose HTML from the drop-down list. Give the filename an extension of . html, specify the file location, and click Save. The converted file is saved where you specified.

How do I view HTML on iPhone?

Now you can use go to any webpage using mobile Safari (and Chrome) on your iDevice (iPhone, iPod, or iPad), tap the Bookmarks icon then tap the Show Page Source bookmark, and a new window opens displaying the source code of the webpage.


1 Answers

The path passed to the UIWebView is incorrect, like Freerunnering mentioned, try this instead:

// Determile cache file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0],@"index.html"];   

// Download and write to file
NSURL *url = [NSURL URLWithString:@"http://www.google.nl"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];

// Load file in UIWebView
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];      

Note: Correct error-handling needs to be added.

like image 186
Anne Avatar answered Oct 13 '22 00:10

Anne