views:

760

answers:

2

My aim: to continue a web session across an app interruption (eg. incoming SMS that is read).

Approach A: I have tried to store the contents of a UIWebView in NSUserDefaults, like this:

NSData *webViewData = [NSKeyedArchiver archivedDataWithRootObject:webView];
[[NSUserDefaults standardUserDefaults] setObject:webViewData forKey:kDefaultsWebViewObjectKey];

and then restore it like:

NSData *dta = [[NSUserDefaults standardUserDefaults] objectForKey:kDefaultsWebViewObjectKey];
webView = [NSKeyedUnarchiver unarchiveObjectWithData:dta];

but that does not include the contents.

Approach B: I have also tried getting the contents of the UIWebView with:

NSString *content = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML;"];

then storing it, and retrieving it again, and then trying to set it in the UIWebView with:

- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL

but the innerHTML javascript is not returning the whole content.

Any ideas, suggestions, etc.?

A: 

If your document doesn't reference any resources (or does so explicitly), you should be able to restore the outerHTML:

NSString *content = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML;"];

For the smoothest experience you will have to also restore the scroll and zoom properties and show a cached representation while the webview is loading

rpetrich
unfortuneatly that return an empty string
Uffe Koch
Oops, it should be document.documentElement.outerHTML
rpetrich
A: 

I ended up using NSURLRequests, and then storing the retrieved HTTP body and cookies to NSUserDefaults.

After the re-entry to the app I read these and set them again on a UIWebView and in the NSHTTPCookieStorage, and then clearing the NSUserDefaults for these keys.

Uffe Koch