Reputation: 1497
Ionic 2 storage not working on ios but working on Android. I am using this one import { Storage } from '@ionic/storage';
to store data locally.
I made sample like this
import { Storage } from '@ionic/storage';
export class MyApp {
constructor(private storage: Storage) { }
setData() {
// set a key/value
storage.set('username', 'johndoe');
}
getData() {
// get a key/value pair
storage.get('username').then((val) => {
alert('Your username is', val);
});
}
}
It works perfectly on Android. But when I try to build on iOS, it doesn't work. Data is not showing. Some recommendation on how to store persistent data in ionic 2 that works perfectly on android and iOS platforms.
Upvotes: 3
Views: 2056
Reputation: 6620
First, I don't see your main module definition, so I'll touch on that point first. In your main app module you need to have an import for IoinicStorageModule
and then you need to put this in your imports
section:
imports:[IonicStorageModule.forRoot({'yourappname'})]
Second, I don't see you checking to see if storage is ready, and you should probably do that too:
this.storage.ready()
.then(() => {
this.storage.set(key, value);
});
Lastly, your local storage issues can easily be solved with this simple service:
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable()
export class LocalStorageService {
constructor(private storage: Storage){
}
public setValue(key: string, value: string): Promise<boolean> {
return this.storage.ready()
.then(() => {
return this.storage.set(key, value)
.catch(() => {
return null;
});
});
//TODO: Handle storage not being available
}
public getValue(key: string): Promise<string> {
return this.storage.ready()
.then(() => {
return this.storage.get(key)
.catch(() => {
return null;
});
});
//TODO: Handle storage not being available
}
}
I use this on a daily basis. Don't forget to wrap some unit tests around it.
Upvotes: 2
Reputation: 65860
If you'll install SQLite plugin then you'll not have any issue on iOS too.
Here is the SQLite plugin.
When running in a native app context, Storage will prioritize using SQLite, as it's one of the most stable and widely used file-based databases, and avoids some of the pitfalls of things like localstorage and IndexedDB, such as the OS deciding to clear out such data in low disk-space situations.
Upvotes: 0