Yazzmi
Yazzmi

Reputation: 1571

Cache a webpage on the iPhone with UIWebView

How can I load a web page when internet is available and cache it for offline use and it updates to the latest version when internet becomes available again?

Upvotes: 0

Views: 1334

Answers (1)

mvds
mvds

Reputation: 47034

I assume some basic skills are available. This is a general outline.

Get the webpage using:

NSData *data = [NSData dataWithContentsOfUrl:yoururl];

If successful, store the file locally using:

-(NSString*)cacheFile
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                                                          NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"cached.html"];
}

[[NSFileManager defaultManager]
               createFileAtPath:[self cacheFile] contents:data attributes:nil];

let the webview show the local page:

NSData *data = [NSData dataWithContentsOfFile:[self cacheFile]
                       options:nil error:nil];

[webView loadData:data MIMEType:@"text/html"
         textEncodingName:@"UTF-8" baseURL:yoururl];

Don't know if you can get away with all the nil pointers I put in here, but if it doesn't work just look up the docs. And do add some checking of return values...

Upvotes: 1

Related Questions