views:

84

answers:

1

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?

A: 

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...

mvds
how and where do you check whether internet is available?
Yazzmi
The request simply fails, I think, returning `nil`. Otherwise you maybe need to take the more elaborate road of `+ (id)dataWithContentsOfURL:(NSURL *)aURL options:(NSDataReadingOptions)mask error:(NSError **)errorPtr`, which would be more verbose on what goes wrong.
mvds