首选项数据持久化实现用户登录记住密码和自动登录

用户登录,点击记住密码和自动登录,使用首选项保存用户账号密码以及是否记住密码和自动登录状态。再次登陆时,如已记住密码,则账号密码不用再次输入,如勾选自动登录,则过5秒后自动登录

HarmonyOS
2024-05-22 23:07:41
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
gdycp

使用的核心API

@ohos.data.preferences

@ohos.router

核心代码解释

点击登录按钮,先判断账号秘钥是否正确,再写入账号。如果勾选了记住秘钥,就写入秘钥和记住秘钥的状态,没有就删除秘钥和记住秘钥的状态。然后判断如果勾选了自动登录,写入自动登录的状态,没有就删除其状态。最后持久化数据并跳转页面。

if (this.inputAccountValue == usernameV && this.inputPassword == passwordV) { 
​ 
try { 
  //添加数据,写入账号 
  if (this.preferences.hasSync('username')) { 
    //如果存在就更改账号 
    this.preferences.put('username', this.inputAccountValue, (err: BusinessError) => { 
      if (err) { 
        console.error(`Failed to put the value of 'username'. Code:${err.code},message:${err.message}`); 
        return; 
      } 
    }) 
  } else { 
    // 此处以此键值对不存在时写入数据为例 
    this.preferences.putSync('username', this.inputAccountValue); 
  } 
​ 
  //点击记住秘钥,持久化账号秘钥 
  if (this.flag1 == true){ 
    //写入秘钥 
    if (this.preferences.hasSync('password')) { 
      //如果存在就更改秘钥 
      this.preferences.put('password', this.inputPassword, (err: BusinessError) => { 
        if (err) { 
          console.error(`Failed to put the value of 'password'. Code:${err.code},message:${err.message}`); 
          return; 
        } 
      }) 
    } else { 
      // 键值对不存在时写入数据 
      this.preferences.putSync('password', this.inputPassword); 
    } 
    //写入记住秘钥状态 
    if (this.preferences.hasSync('savePassword')) { 
    } else { 
      // 键值对不存在时写入数据 
      this.preferences.putSync('savePassword', this.flag1); 
    } 
​ 
    //写入自动登录状态 
    if (this.flag2 == true){ 
      if (this.preferences.hasSync('autoLogin')) { 
      } else { 
        // 此处以此键值对不存在时写入数据为例 
        this.preferences.putSync('autoLogin', this.flag1); 
      } 
    }else { 
      this.preferences.deleteSync('autoLogin'); 
    } 
  }else { 
    this.preferences.deleteSync('password'); 
    this.preferences.deleteSync('savePassword'); 
  } 
​ 
  //数据持久化 
  this.preferences.flush((err: BusinessError) => { 
    if (err) { 
      console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); 
      return; 
    } 
    console.info('Succeeded in flushing.'); 
  }) 
​ 
} catch (err) { 
  let code = (err as BusinessError).code; 
  let message = (err as BusinessError).message; 
  console.error(`Failed to check the key 'save'. Code:${code}, message:${message}`); 
} 
​ 
router.pushUrl({url: 'pages/Loading'}); 
}else { 
console.error(`Failed to check the key 'login'`); 
}

应用初次加载时读取本地数据

let preferences: dataPreferences.Preferences = {} as dataPreferences.Preferences; 
export default class EntryAbility extends UIAbility { 
//组件创建时加载本地数据 
  try { 
    let options: dataPreferences.Options = {name: 'myStore'}; 
    preferences = dataPreferences.getPreferencesSync(this.context, options); 
    AppStorage.setOrCreate("preferences",preferences); 
  } catch (err) { 
    let code = (err as BusinessError).code; 
    let message = (err as BusinessError).message; 
    console.error(`Failed to get preferences. Code:${code},message:${message}`); 
  } 
​ 
  //写入数据 
  try { 
    if (preferences.hasSync('startup')) { 
      console.info("The key 'startup' is contained."); 
    } else { 
      console.info("The key 'startup' does not contain."); 
      // 此处以此键值对不存在时写入数据为例 
      preferences.putSync('startup', 'auto'); 
    } 
  } catch (err) { 
    let code = (err as BusinessError).code; 
    let message = (err as BusinessError).message; 
    console.error(`Failed to check the key 'startup'. Code:${code}, message:${message}`); 
  } 
}

获取应用加载时preferences获取的数据

@StorageLink("preferences") preferences:dataPreferences.Preferences = {} as dataPreferences.Preferences;

在页面初次加载时,获取preferences里存储的用户信息和状态

aboutToAppear(){ 
try { 
  let usernameVal: Object = this.preferences.getSync('username', 'default'); 
  this.username = usernameVal as string; 
  if (this.username == "default") { 
    this.username = ""; 
  } 
  let passwordVal: Object = this.preferences.getSync('password', 'default'); 
  this.password = passwordVal as string; 
  if (this.password == "default") { 
    this.password = ""; 
  } 
  let savePasswordVal: Object = this.preferences.getSync('savePassword', 'default'); 
  if (savePasswordVal != DEFAULT) { 
    this.flag1 = savePasswordVal as boolean; 
  } 
  let autoLoginVal: Object = this.preferences.getSync('autoLogin', 'default'); 
  if (autoLoginVal != DEFAULT) { 
    this.flag2 = autoLoginVal as boolean; 
  } 
  console.info(`Succeeded in getting value of 'info'. usernameVal: ${usernameVal}.passwordVal: ${passwordVal}.savePasswordVal: ${savePasswordVal}.autoLoginVal: ${autoLoginVal}.`); 
} catch (err) { 
  let code: number = (err as BusinessError).code; 
  let message: string = (err as BusinessError).message; 
  console.error(`Failed to get value of 'info'. Code:${code}, message:${message}`); 
} 
}

页面每次加载时判断是否自动登录,如果是自动登录且账号秘钥正确,则5秒后登录

//加载等待 
async function sleepFunction(): Promise<void> { 
try { 
  const result: string = await new Promise(() =>{ 
    setTimeout(()=>{ 
      router.pushUrl({url: 'pages/Loading'}); 
    }, 5000); 
  }); 
}catch (e) { 
  console.error(`Get exception: ${e}`); 
} 
} 
onPageShow(){ 
if (this.flag2 == true && this.username == usernameV && this.password == passwordV) { 
  sleepFunction() 
} 
}

主体代码Index页面

import dataPreferences from '@ohos.data.preferences'; 
import { BusinessError } from '@ohos.base'; 
import { DEFAULT } from '@ohos/hypium'; 
import router from '@ohos.router'; 
​ 
const usernameV: string = "admin"; 
const passwordV: string = "123456"; 
​ 
//加载等待 
async function sleepFunction(): Promise<void> { 
try { 
  const result: string = await new Promise(() =>{ 
    setTimeout(()=>{ 
      router.pushUrl({url: 'pages/Loading'}); 
    }, 5000); 
  }); 
}catch (e) { 
  console.error(`Get exception: ${e}`); 
} 
} 
​ 
@Entry 
@Component 
struct Index { 
@State message: string = 'Hello World'; 
private inputAccountValue : string = ""; 
private inputPassword : string = ""; 
@State flag1: boolean = false; 
@State flag2: boolean = false; 
private username: string = ""; 
private password: string = ""; 
​ 
@StorageLink("preferences") preferences:dataPreferences.Preferences = {} as dataPreferences.Preferences; 
​ 
aboutToAppear(){ 
  try { 
    let usernameVal: Object = this.preferences.getSync('username', 'default'); 
    this.username = usernameVal as string; 
    if (this.username == "default") { 
      this.username = ""; 
    } 
    let passwordVal: Object = this.preferences.getSync('password', 'default'); 
    this.password = passwordVal as string; 
    if (this.password == "default") { 
      this.password = ""; 
    } 
    let savePasswordVal: Object = this.preferences.getSync('savePassword', 'default'); 
    if (savePasswordVal != DEFAULT) { 
      this.flag1 = savePasswordVal as boolean; 
    } 
    let autoLoginVal: Object = this.preferences.getSync('autoLogin', 'default'); 
    if (autoLoginVal != DEFAULT) { 
      this.flag2 = autoLoginVal as boolean; 
    } 
    console.info(`Succeeded in getting value of 'info'. usernameVal: ${usernameVal}.passwordVal: ${passwordVal}.savePasswordVal: ${savePasswordVal}.autoLoginVal: ${autoLoginVal}.`); 
  } catch (err) { 
    let code: number = (err as BusinessError).code; 
    let message: string = (err as BusinessError).message; 
    console.error(`Failed to get value of 'info'. Code:${code}, message:${message}`); 
  } 
} 
​ 
onPageShow(){ 
  if (this.flag2 == true && this.username == usernameV && this.password == passwordV) { 
    sleepFunction() 
  } 
} 
​ 
build() { 
  Row() { 
    Column() { 
      Text(this.message) 
        .fontSize(50) 
        .fontWeight(FontWeight.Bold) 
      Row(){ 
        Text("账号:") 
          .margin({top: 20}) 
          .fontSize(20) 
        TextInput({placeholder:'请输入账号', text: this.username}) 
          .onChange((value: string) => { 
            this.inputAccountValue = value; 
          }) 
          .width(250) 
          .margin({top: 20}) 
          .type(InputType.Normal) 
      } 
      Row(){ 
        Text("秘钥:") 
          .margin({top: 20}) 
          .fontSize(20) 
        TextInput({placeholder:'请输入秘钥', text: this.password}) 
          .onChange((value: string) => { 
            this.inputPassword = value; 
          }) 
          .width(250) 
          .margin({top: 20}) 
          .type(InputType.Password) 
      } 
      Row(){ 
        Row(){ 
          Toggle({ type: ToggleType.Checkbox, isOn: this.flag1 }) 
            .margin({top: 13}) 
            .width(20) 
            .onClick(()=>{ 
              this.flag1 = !this.flag1; 
            }) 
          Text("记住秘钥") 
            .margin({top: 10}) 
            .fontSize(15) 
        } 
        .margin({right:50}) 
        Row(){ 
          Toggle({ type: ToggleType.Checkbox, isOn: this.flag2 }) 
            .margin({top: 13}) 
            .width(20) 
            .onClick(()=>{ 
              if (this.flag2 == false) { 
                this.flag1 = true; 
              } 
              this.flag2 = !this.flag2; 
            }) 
          Text("自动登录") 
            .margin({top: 10}) 
            .fontSize(15) 
        } 
        .margin({left:50}) 
      } 
​ 
      Button('登录') 
        .width(150) 
        .margin({ top: 20 }) 
        .onClick(()=>{ 
​ 
          if (this.inputAccountValue == usernameV && this.inputPassword == passwordV) { 
​ 
            try { 
              //添加数据,写入账号 
              if (this.preferences.hasSync('username')) { 
                //如果存在就更改账号 
                this.preferences.put('username', this.inputAccountValue, (err: BusinessError) => { 
                  if (err) { 
                    console.error(`Failed to put the value of 'username'. Code:${err.code},message:${err.message}`); 
                    return; 
                  } 
                }) 
              } else { 
                // 此处以此键值对不存在时写入数据为例 
                this.preferences.putSync('username', this.inputAccountValue); 
              } 
​ 
              //点击记住秘钥,持久化账号秘钥 
              if (this.flag1 == true){ 
                //写入秘钥
                if (this.preferences.hasSync('password')) { 
                  //如果存在就更改秘钥 
                  this.preferences.put('password', this.inputPassword, (err: BusinessError) => { 
                    if (err) { 
                      console.error(`Failed to put the value of 'password'. Code:${err.code},message:${err.message}`); 
                      return; 
                    } 
                  }) 
                } else { 
                  // 键值对不存在时写入数据 
                  this.preferences.putSync('password', this.inputPassword); 
                } 
                //写入记住秘钥状态 
                if (this.preferences.hasSync('savePassword')) { 
                } else { 
                  // 键值对不存在时写入数据 
                  this.preferences.putSync('savePassword', this.flag1); 
                } 
​ 
                //写入自动登录状态 
                if (this.flag2 == true){ 
                  if (this.preferences.hasSync('autoLogin')) { 
                  } else { 
                    // 此处以此键值对不存在时写入数据为例 
                    this.preferences.putSync('autoLogin', this.flag1); 
                  } 
                }else { 
                  this.preferences.deleteSync('autoLogin'); 
                } 
              }else { 
                this.preferences.deleteSync('password'); 
                this.preferences.deleteSync('savePassword'); 
              } 
​ 
              //数据持久化 
              this.preferences.flush((err: BusinessError) => { 
                if (err) { 
                  console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); 
                  return; 
                } 
                console.info('Succeeded in flushing.'); 
              }) 
​ 
            } catch (err) { 
              let code = (err as BusinessError).code; 
              let message = (err as BusinessError).message; 
              console.error(`Failed to check the key 'save'. Code:${code}, message:${message}`); 
            } 
​ 
            router.pushUrl({url: 'pages/Loading'}); 
          }else { 
            console.error(`Failed to check the key 'login'`); 
          } 
​ 
        }) 
    } 
    .width('100%') 
  } 
  .height('100%') 
} 
}

加载页面loading,5秒后跳转首页

import router from '@ohos.router' 
​ 
​ 
//加载等待 
async function sleepFunction(): Promise<void> { 
try { 
  const result: string = await new Promise(() =>{ 
    setTimeout(()=>{ 
      router.pushUrl({url: 'pages/HomePage'}); 
    }, 5000); 
  }); 
}catch (e) { 
  console.error(`Get exception: ${e}`); 
} 
} 
​ 
@Entry 
@Component 
struct Loading{ 
 
onPageShow(){ 
  sleepFunction(); 
} 
​ 
build(){ 
  Row(){ 
    Column(){ 
      Image($r('app.media.icon')) 
        .width(50) 
        .margin({bottom: 20}) 
      Text("loading...") 
        .fontSize(25) 
    } 
    .width('100%') 
  } 
  .height('100%') 
  .width('100%') 
} 
}

主页HomePage,有退出登录按钮

import router from '@ohos.router' 
​ 
@Entry 
@Component 
struct HomePage{ 
​ 
build(){ 
  Row(){ 
    Column(){ 
      Image($r('app.media.icon')) 
        .width(50) 
        .margin({bottom: 20}) 
      Text("首页") 
        .fontSize(25) 
      Button("退出登录") 
        .onClick(()=>{ 
          //router.back({url: 'pages/Index'}) 
          router.pushUrl({url:'pages/Index'}) 
        }) 
    } 
    .width('100%') 
  } 
  .height('100%') 
  .width('100%') 
} 
}

适配版本

DevEco Studio Version: 4.0.1.601

SDK:HarmoneyOS 4.0.10.11

分享
微博
QQ
微信
回复
2024-05-23 17:54:58
相关问题
首选项获取实例,实例是否为单例
706浏览 • 1回复 待解决
错误码15500000(首选项)如何处理?
526浏览 • 1回复 待解决
如何实现应用数据持久存储
806浏览 • 1回复 待解决
密码或验证码登录页面完整代码
476浏览 • 1回复 待解决
求大佬告知如何实现数据持久
40浏览 • 1回复 待解决
卡片开发中如何实现数据持久
834浏览 • 1回复 待解决
关于数据持久存储要如何实现
84浏览 • 2回复 待解决
JS 如何实现登录 连接后端?
2437浏览 • 1回复 待解决
数据持久的方式有哪些?
416浏览 • 1回复 待解决
PersistentStorage实现手机号登录匹配
468浏览 • 1回复 待解决
如何通过卡片点击实现业务登录场景
649浏览 • 1回复 待解决
如何在IDE每次run项目后数据持久
503浏览 • 1回复 待解决
devecostudio登录后无设备
3499浏览 • 3回复 已解决