Search code examples
iostypescriptcordovaionic3ionic-native

ionic native storage does not work on iOS


I use Ionic 3 on one of my projects with an authentication system. I use native storage when the user wants to connect. It works on Android but on iOS, it redirects me to the login screen even using platform.ready (). I saw that several people were a similar problem but no answer, so I wanted to know if someone was facing the same problem and if he found a solution. Here is my code:

this.plt.ready().then(() => {
                            this.nativeStorage.setItem('userStorage', { stayConnected: (typeof this.stayConnected == "undefined" || this.stayConnected == false ? '' : 'stayConnected'), userId: (result as any).id, userLogin: (result as any).login })
                                .then(
                                    () => {
                                        this.loader.dismiss();
                                        this.navCtrl.setRoot(HomePage);
                                    },
                                    error => {
                                        this.loader.dismiss();
                                        this.presentToast(this.languageLogin.error, 3000, "bottom");
                                    }
                                )
                        }, 
                        error => {
                            this.loader.dismiss();
                            this.presentToast(this.languageLogin.error, 3000, "bottom");
                        });

thank you for your answers.


Solution

  • I would put 2 function storeUser() and getUser() into the same provider UserService like belows Then add UserService to the constructor of any pages required. It works for both IOS, Android and web

    import {Storage} from '@ionic/storage';
    import {Observable} from 'rxjs/Observable';
    @Injectable()
    export class UserService {
     constructor(private storage: Storage){}
     public storeUser(userData): void {
         this.storage.set('userData', userData);
    }
    public getUser(): Observable<any>
      return Observable.fromPromise(this.storage.get('userData').then((val) => {
                return !!val;
            }));
    }