iOS 7 webview and localStorage persistence

2019-01-23 04:37发布

问题:

I'm developing a hybrid app (for iOS and Android only) using PhoneGap/Cordova and want to use HTML5 localStorage to store content for offline access.

http://caniuse.com/#search=localStorage says - "In iOS 5 & 6 localStorage data is stored in a location that may occasionally be cleared out by the OS."

  1. What is the situation with an iOS 7 (and later) webview, in what cases will localStorage persist, or get cleared out (by the OS, or the user)?

  2. Will an update to the app clear localStorage?

  3. What about the user clearing browser history on Safari - will that apply to the webview too?

  4. Do I need to worry (or can I even control) where on the fils system the localStorage is created. I understand it should not be backed up on iCloud.


I got a device (iPad) and checking the file system I see that localStorage file is in ~/Library/Caches within the app sandbox, see image below.

From the docs:

https://developer.apple.com/icloud/documentation/data-storage/index.html Data that can be downloaded again or regenerated should be stored in the /Library/Caches directory. Examples of files you should put in the Caches directory include database cache files and downloadable content, such as that used by magazine, newspaper, and map applications.

I am simply doing this to set data:

  localStorage.setItem('foo','this is the FOO value');
  localStorage.setItem('bar','and this is the BAR value');

回答1:

If you are using cordova, that problem was fixed long time ago, even for iOS 5 and iOS 6. You shouldn't worry if you are using the latest version of cordova.



回答2:

If you do still face the issue with Cordova-iOS v4 , then try the NativeStorage plugin. https://www.npmjs.com/package/cordova-plugin-nativestorage.

It has set, put and get functions which implement platform capabilities like android shared preferences and iOS NSUserDefaults which makes data store as safe as allowed.

cordova plugin add cordova-plugin-nativestorage

NativeStorage.putObject("reference_to_value",<object>, <success-callback>, <error-callback>);

NativeStorage.getObject("reference_to_value",<success-callback>, <error-callback>);


回答3:

Your best bet is to use the NativeStorage plugin:

https://www.npmjs.com/package/cordova-plugin-nativestorage

To answer your questions:

  1. The localStorage data is kept in a cache directory in the filesystem, and cache is cleaned by the OS frequently (for example when the device is low on disk space).
  2. No, updating the app won't clear local storage.
  3. No, Safari local storage and Webview local storage are separate.
  4. No, you cannot control where on the filesystem it's stored.