首页 > 解决方案 > Sqlite Ionic:IOS设备找不到数据库

问题描述

我正在使用 Ionic 构建 iOS 和 Android 应用程序。我想在用户第一次登录后存储用户记录,以便他们在关闭应用程序后不必再次登录。因此,当应用程序启动时,它会通过表中是否有用户记录来检查他们是否“登录”。如果没有登录(他们第一次运行应用程序或稍后单击“注销”),那么它应该进入登录页面。

app.component.ts

this.platform.ready().then(() => { 
          this.registerBackButton();
          this.statusBar.styleDefault(); 
          this.sqlStorageService.initializeDatabase().then(()=> {  
            this.sqlStorageService.isLoggedIn().then(loggedIn => { 
              this.loader.dismiss();
              this.splashScreen.hide();
              if (loggedIn){  
                this.rootPage = HomePage;
                }else{   
                  this.rootPage = LoginPage;
                }   
            });
        }); 

sqlStorageService 中

initializeDatabase()
  { 
      return this.sqlite.create({name: 'data.db', location: 'default' }).then(db => {
          this.db = db; 
          return this.db.executeSql('CREATE TABLE IF NOT EXISTS CurrentUser(userName text primary key, firstName text, lastName text, bearerToken text, claims text)', [])
          .then(data => {console.log("initialize database complete")})
      })
  }

isLoggedIn():Promise<boolean>{
    return this.get().then(data => {
        return data != null;
    }) 
}


get() : Promise<IAppUserAuthorization> | null{  
    return this.db.executeSql('SELECT userName, firstName, lastName, bearerToken, claims FROM CurrentUser', [])
        .then(data => {   
            if (data.rows.length == 0){
                return null;
            } 

            let user: IAppUserAuthorization =
            {
                userName: data.rows.item(0).userName,
                firstName: data.rows.item(0).firstName,
                lastName: data.rows.item(0).lastName,
                bearerToken: data.rows.item(0).bearerToken,
                isAuthenticated: data.rows.item(0).isAuthenticated,
                claims: JSON.parse(data.rows.item(0).claims) 

            }  
            return user;  
    })   
}  

用户认证后

 return this.db.executeSql('insert or replace into CurrentUser(userName, firstName, lastName, bearerToken, claims) values(?, ?, ? , ?, ?)',
        [appUser.userName, appUser.firstName, appUser.lastName, appUser.bearerToken, JSON.stringify(appUser.claims)])
            .then(data => { 
        return JSON.parse(data.rows.item(0).value); 
      }); 

当我部署到安卓设备时,这一切都很好。我是第一次登录。然后关闭应用程序...然后重新打开应用程序,我被带到主页。

当我部署到任何 iOS 设备时,我都会第一次登录。然后关闭应用程序..然后重新打开应用程序,我被带到登录页面。

我想指出的是,在我登录 iOS 设备并通过身份验证后。记录存储在数据库中,我可以从代码的任何其他部分访问表中的数据,它按预期工作。只有当我关闭应用程序并重新打开它时它才不起作用。好像没找到数据库(或者那个表里没找到数据)

我已经为此头疼了3天了。我确定它确实很微妙,但我不明白为什么它可以完美地适用于 android 而不是 iOS

标签: androidiossqliteionic3

解决方案


推荐阅读