NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:self.webView forKey:@\"webView\"];
The code above is made to save
There is no easy answer here. The WKWebView cannot be archived and it does also not participate in UI state preservation/restoration. You already discovered this.
For Firefox for iOS we took a different route to work around these limitations. This far from ideal but it does work.
When we restore a tab that has session info (previously visited pages) attached, we load a special html page from a local web server (running on localhost) that modifies the push state of the page and pushes previously visited URLs on the history stack.
Because these URLs need to be of same origin, we basically push urls like `http://localhost:1234/history/item?url=http://original.url.com
In our UI we translate this to display original.url.com
. When the user goes back in history to load these, we intercept and instead of loading the page from localhost, we load the original page.
It is a big hack but that is all we have at this point.
See the source code at https://github.com/mozilla/firefox-ios
you can only store certain types of objects in NSUserDefaults, namely
NSArray
NSData
NSDate
NSDictionary
NSNumber
NSString
(you cant bypass this by putting your webview inside an NSArray)
what you could do is store relevant information about the webview in an NSDictionary that would allow you to be able to get your webview back into its current state when loading from the NSUserDefaults
you can refer to the documentation for more details
In case you really want the webview from user default, here is a choice.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[NSKeyedArchiver archivedDataWithRootObject:self.webView] forKey:@"webView"];
// get it back from user default
NSData *data = [prefs objectForKey:@"webView"];
self.webView = [NSKeyedUnarchiver unarchiveObjectWithData:data];
As @fonix mentioned, you can only store a select few data types in NSUserDefault
.
If you just wanted the url, it would be pretty easy to convert that to a string and save it to NSUserDefaults
.
However, the crux of the question is how to "restore the WKWebview
with its history intact."
Since, to 'save' the web view, you want not only the current URL being shown, but also the history, you need access the backForwardList
on WKWebview.
NSMutableArray *history = [NSMutableArray array];
for(WKBackForwardListItem *item in webview.backForwardList.backList){
// use -absoluteString to convert NSURL to NSString
[history addObject:[item.url absoluteString]];
}
[[NSUserDefaults standardUserDefaults] addObject:history forKey:@"webviewHistory"];
[[NSUserDefaults standardUserDefaults] synchronize];
Saving those URLS into an NSArray
, will allow you to save them to NSUserDefaults
.
Then when you want to 'recreate' the webview, iterate through this array and request each url to simulate the history.
Hope this helps!