We are transitioning away from PhoneGap to a truly native iPhone app and we need to access user data stored in HTML5 local storage created by PhoneGap. How do we get at that data so that we can create a seamless update process for the user?
I haven't tried Mattias' way but I just accessed the webkit local storage database directly and then imported the sqlite3 lib included with the iPhone SDK to extract the values I needed. This is how you access localstorage created by PhoneGap:
NSString *databaseName = @"file__0.localstorage";
//Get Library path
NSArray *libraryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask, YES);
NSString *libraryDir = [libraryPaths objectAtIndex:0];
NSString *databasePath = [libraryDir
stringByAppendingPathComponent:@"WebKit/LocalStorage/"];
NSString *databaseFile = [databasePath
stringByAppendingPathComponent:databaseName];
BOOL webkitDb;
NSFileManager *fileManager = [NSFileManager defaultManager];
webkitDb = [fileManager fileExistsAtPath:databaseFile];
if (webkitDb) {
MMWebKitLocalStorageController* wkc = [[MMWebKitLocalStorageController alloc] init];
[wkc updateUserFromLocalStorage:databaseFile];
}
I don't think there is currently any native API for accessing the local storage but you could try to create a web view with some JavaScript that dumps the local storage to i.e. JSON.
Create a UIWebView
that has a UIWebViewDelegate
delegate that implements the webViewDidFinishLoad:
method and uses the stringByEvaluatingJavaScriptFromString:
method to trigger a dump.
Something like this, first the page to load in the web view:
<html>
<head>
<script>
// download and insert JSON-js here
// https://github.com/douglascrockford/JSON-js
function dumpLocalStorageToJSON() {
d = {};
for(i = 0; i < localStorage.length; i++)
d[localStorage.key(i)] = localStorage.getItem(localStorage.key(i));
return JSON.stringify(d);
}
</script>
</head>
</html>
Then the finish load delegate method:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *localStorageAsJSON = [webView stringByEvaluatingJavaScriptFromString:@"dumpLocalStorageToJSON();"];
// parse JSON and do something useful
}
I just provide some detail FYI,the LocalStorage save in the database whitch path is
Library/WebKit/LocalStorage/
(UIWebview)Library/Caches/
(UIWebview)Library/WebKit/WebsiteData/LocalStorage/
(WKWebView)Then open the database,execute query SELECT key,value FROM ItemTable
can get key
and value
.The key is NSString,value is NSData,encode with NSUTF16LittleEndianStringEncoding
,convert to NSString with code:
[[NSString alloc] initWithData:data encoding:NSUTF16LittleEndianStringEncoding];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With