IONIC 2 - 从短信读取OTP并登录dashbord

时间:2018-04-11 11:37:17

标签: angularjs ionic2

我正在进行自动验证otp ionic2。在那,应用SMS权限,如果设备移动号码存在或从sms读取otp然后它直接切换到仪表板页面我使用一个名为watchSMS()的函数,如角度代码所示,但它给出一个错误(SMS没有定义)。

任何帮助都将受到高度赞赏。

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController, Platform, LoadingController, ToastController, ViewController } from 'ionic-angular';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { Network } from '@ionic-native/network';
import { CrudHttpProvider } from '../../providers/crud-http/crud-http';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { ConstantVariable } from '../../app/constant-variable';
import { HomePage } from '../home/home';
// import { SMS } from '@ionic-native/sms';
import { Sim } from "@ionic-native/sim";
import { AndroidPermissions } from '@ionic-native/android-permissions';

declare var window: any;
declare var SMS:any;

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  public myForm: FormGroup;  
  public mobile: any;
  public db_name: any;
  public url_play_store: any;
  public buttonDisabled: any;

  public studname: any;
  public tuition_name: any;
  public prn: any;
  public otp: any;
  public api_key: any;

  public userinfo:any;
  public stored_mb:any;

  public simInfo: any;
  public cards: any;
  public phoneNumber: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, public alertCtrl: AlertController, public platform: Platform, public network: Network, public loadingCtrl: LoadingController, public toastCtrl: ToastController, public crudHttpProvider: CrudHttpProvider, public sqlite: SQLite, public viewCtrl: ViewController, public sim: Sim, public androidPermissions: AndroidPermissions) {


    this.db_name = ConstantVariable.db_name;

    this.myForm = this.formBuilder.group({
      'mobile': ['', [Validators.required]],
    }); 

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  login() {

    let post_data = { 'api_url': 'checkMobileNumber', "post": {'mobile': this.mobile} };
    this.crudHttpProvider.callToCrudPost(post_data)
      .then(data => {

        let res = data;
        if (res['status'] == 100) {

          this.studname     = res['data'].studname;
          this.tuition_name = res['data'].tuition_name;
          this.prn          = res['data'].prn;
          this.otp          = res['data'].otp;
          this.api_key      = res['data'].api_key;

          this.navCtrl.push('RegisterPage',{
            "studname":     this.studname,
            "tuition_name": this.tuition_name,
            "prn":          this.prn,                                                           
            "otp":          this.otp,                                                          
            "api_key":      this.api_key                                                                
          });
          this.viewCtrl.dismiss();

          this.checkPermission(); 

        } 
      });

  }

  checkPermission() {
    this.androidPermissions.checkPermission
    (this.androidPermissions.PERMISSION.READ_SMS).then(
    success => {

    //if permission granted
    this.watchSMS();
    },
    err =>{

    this.androidPermissions.requestPermission
    (this.androidPermissions.PERMISSION.READ_SMS).
    then(success=>{
      this.watchSMS();
    },
    err=>{
    alert("cancelled")
    });
    });

    this.androidPermissions.requestPermissions
    ([this.androidPermissions.PERMISSION.READ_SMS]);

  }

  watchSMS() {   
    if(window.SMS) window.SMS.startWatch(function(){  
      console.log('Succeed to start watching SMS'); 
      this.navCtrl.push('DashboardPage');

      let toast = this.toastCtrl.create({
        message: "Succeed to start watching SMS.",
        duration: 4000
      });
      toast.present();

      document.addEventListener('onSMSArrive', this.smsArived);
    }, function(){   
      console.log('failed to start watching SMS');  

      let toast = this.toastCtrl.create({
        message: "failed to start watching SMS.",
        duration: 4000
      });
      toast.present();
    });  

  }

  stopWatchSMS() {   
    if(window.SMS) window.SMS.stopWatch(function(){ 
       console.log('Succeed to stop watching SMS'); 
    }, function(){  
       console.log('failed to stop watching SMS');    
    }); 
  }

  smsArived = (result: any) => { 
      console.log("SMS DATA 2" + result);

      let toast = this.toastCtrl.create({
        message: "RESULT " + result,
        duration: 4000
      });
      toast.present();

      this.stopWatchSMS();   
  }

}

1 个答案:

答案 0 :(得分:2)

我通过此tutorial实现了自动验证OTP。我没遇到麻烦。 在platform.ready()内部调用SMS,它说:"确保始终在platform.ready()内的Ionic Framework中使用方法,否则它将无效。"。最后,我想,你不需要使用窗口。

ionViewDidEnter()
    {

    this.platform.ready().then((readySource) => {
    if(SMS) SMS.startWatch(()=>{
               console.log('watching started');
            }, Error=>{
           console.log('failed to start watching');
       });

      document.addEventListener('onSMSArrive', (e:any)=>{
           var sms = e.data;
           console.log(sms);

           });

        });
    }