簡體   English   中英

如果用戶已經登錄Ionic Facebook集成應用程序,如何避免Facebook登錄屏幕

[英]How to avoid Facebook LogIn screen if user already logged in in Ionic facebook integration app

我正在從事離子項目,進入應用程序的唯一方法是通過Facebook登錄。

默認頁面將是登錄頁面。

問題是每次我打開該應用程序時都會出現登錄頁面,那么如果用戶已經登錄,如何避免登錄頁面呢?

我的默認路徑是登錄頁面,但是如果用戶已經登錄,我會盡量避免登錄頁面。

app.js

var wowzer = angular.module('wowzer', ['ionic'])
wowzer.config(function($stateProvider, $urlRouterProvider, $locationProvider) {

  $stateProvider
    .state('login', {
      url: '/',
      templateUrl: 'templates/login.html',
      controller: 'LoginCtrl'
    })
    .state('app', {
      url: '/app',
      abstract: true,
      templateUrl: 'templates/menu.html',
      controller: 'LoginCtrl'
    })

    .state('app.search', {
      url: '/search',
      views: {
        'menuContent': {
          templateUrl: 'templates/search.html'
        }
      }
    })

    .state('app.browse', {
      url: '/browse',
      views: {
        'menuContent': {
          templateUrl: 'templates/browse.html'
        }
      }
    })
    .state('app.profileInfo', {
      url: '/profileInfo',
      views: {
        'menuContent': {
          templateUrl: 'templates/profileInfo.html',
          controller: 'ProfileInfoCtrl'
        }
      }
    })

    .state('app.profile', {
      url: '/profile',
      views: {
        'menuContent': {
          templateUrl: 'templates/profile.html',
          controller: 'ProfileCtrl'

        }
      }
    })
    .state('app.dog', {
      url: '/dog',
      views: {
        'menuContent': {
          templateUrl: 'templates/dog.html',
          controller: 'ProfileCtrl'
        }
      }
    });
    $urlRouterProvider.otherwise('/');

});

wowzer.constant('ApiEndpoint', {
  //url:'http://spmean.southindia.cloudapp.azure.com/wowzer'
  url: 'http//192.168.0.62:8100/api'
})

wowzer.run(function($ionicPlatform, $rootScope, $State, UserService) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });


  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if (UserService.getUser()) {
      console.log(UserService.getUser());
      console.log('goto dashboard');
      $state.go('app.profileinfo');
    } else {
      console.log('must login!');
      $state.go('login');
    }
  });

})

wowzer.constant("constantService", {
  attr: "this is first contant"
});

Userservices.js(工廠)

 wowzer.factory('UserService', function() {


  var setUser = function(user_data) {
    window.localStorage.starter_facebook_user = JSON.stringify(user_data);
    console.log(window.localStorage.starter_facebook_user)
  };

  var getUser = function(){
    console.log(window.localStorage.starter_facebook_user)
    return JSON.parse(window.localStorage.starter_facebook_user || '{}');
  };

  return {
    getUser: getUser,
    setUser: setUser
  };

logInController.js

 wowzer.controller('LoginCtrl', function($scope, $state, $ionicModal, $q, $timeout, UserService, $ionicLoading, $ionicActionSheet) { var fbLoginSuccess = function(response) { if (!response.authResponse){ fbLoginError("Cannot find the authResponse"); return; } var authResponse = response.authResponse; getFacebookProfileInfo(authResponse) .then(function(profileInfo) { // For the purpose of this example I will store user data on local storage UserService.setUser({ authResponse: authResponse, userID: profileInfo.id, name: profileInfo.name, email: profileInfo.email, picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large" }); $ionicLoading.hide(); $state.go('app.profileInfo'); }, function(fail){ // Fail get profile info console.log('profile info fail', fail); }); }; // This is the fail callback from the login method var fbLoginError = function(error){ console.log('fbLoginError', error); $ionicLoading.hide(); }; // This method is to get the user profile info from the facebook api var getFacebookProfileInfo = function (authResponse) { var info = $q.defer(); facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null, function (response) { console.log(response); info.resolve(response); }, function (response) { console.log(response); info.reject(response); } ); return info.promise; }; //This method is executed when the user press the "Login with facebook" button $scope.facebookSignIn = function() { facebookConnectPlugin.getLoginStatus(function(success){ if(success.status === 'connected'){ // The user is logged in and has authenticated your app, and response.authResponse supplies // the user's ID, a valid access token, a signed request, and the time the access token // and signed request each expire console.log('getLoginStatus', success.status); // Check if we have our user saved var user = UserService.getUser('facebook'); if(!user.userID){ getFacebookProfileInfo(success.authResponse) .then(function(profileInfo) { // For the purpose of this example I will store user data on local storage UserService.setUser({ authResponse: success.authResponse, userID: profileInfo.id, name: profileInfo.name, email: profileInfo.email, picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large" }); $state.go('app.profile'); }, function(fail){ // Fail get profile info console.log('profile info fail', fail); }); }else{ $state.go('app.profileInfo'); } } else { // If (success.status === 'not_authorized') the user is logged in to Facebook, // but has not authenticated your app // Else the person is not logged into Facebook, // so we're not sure if they are logged into this app or not. console.log('getLoginStatus', success.status); $ionicLoading.show({ template: 'Logging in...' }); // Ask the permissions you need. You can learn more about // FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4 facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError); } }); }; $scope.showLogOutMenu = function() { var hideSheet = $ionicActionSheet.show({ destructiveText: 'Logout', titleText: 'Are you sure you want to logout? This app is awsome so I recommend you to stay.', cancelText: 'Cancel', cancel: function() {}, buttonClicked: function(index) { return true; }, destructiveButtonClicked: function(){ $ionicLoading.show({ template: 'Logging out...' }); // Facebook logout facebookConnectPlugin.logout(function(){ $ionicLoading.hide(); $state.go('login'); }, function(fail){ $ionicLoading.hide(); }); } }); }; }) 

對於離子版本> 1

我使用cordova-plugin-facebook4將facebook集成到離子項目中。 為了存儲登錄的用戶信息,我使用了native-storage 我實際上不記得我關注了哪個博客(那對您會有更多幫助)。 但是下面是我的代碼。

app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { NativeStorage } from '@ionic-native/native-storage';

import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html'
})
export class YahooWhetherApp {
  rootPage:any; // = LoginPage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, public nativeStorage: NativeStorage) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.

      this.setHomePage()
      statusBar.styleDefault();
    });
  }

  setHomePage() {
    let env = this;
      this.nativeStorage.getItem('user').then(function (data) {
        env.rootPage = HomePage;
        this.splashScreen.hide();
      }, function (error) {
        env.rootPage = LoginPage;
        this.splashScreen.hide();
      })
  }

}

登錄名

    import { Component } from '@angular/core';
    import { IonicPage, NavController, NavParams } from 'ionic-angular';
    import { NativeStorage } from '@ionic-native/native-storage';

    import { Facebook } from '@ionic-native/facebook';
    import { Geolocation } from '@ionic-native/geolocation';

    import { HomePage } from '../home/home';

    /**
     * Generated class for the LoginPage page.
     *
     * See http://ionicframework.com/docs/components/#navigation for more info
     * on Ionic pages and navigation.
     */

    @IonicPage()
    @Component({
      selector: 'page-login',
      templateUrl: 'login.html',
    })
    export class LoginPage {
      FB_APP_ID: number = xxxxxxxx;
      latitude: number = null;
      longitude: number = null;
      constructor(public navCtrl: NavController, public navParams: NavParams, public fb: Facebook, public nativeStorage: NativeStorage, private geolocation: Geolocation) {
        this.fb.browserInit(this.FB_APP_ID, "v2.8");
      }

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

      fbLogin() {
        console.log('fBLogin() called!!');
        let permissions = new Array<string>();
        let nav = this.navCtrl;
        let env = this;

        permissions = ["public_profile"];

        this.fb.login(permissions).then(function(response) {
          let userID = response.authResponse.userID;
          let params= new Array<string>();

          //Getting name & gender properties
          env.fb.api("/me?fields=name,gender", params).then(function(user) {
            user.picture = "https://graph.facebook.com/" + userID + "/picture?type=large";
            console.log('getting user fb info');
//Store in loggedIn user's info in device
            env.nativeStorage.setItem('user', {
              name: user.name,
              gender: user.gender,
              picture: user.picture          
            }).then(function() {
              nav.push(HomePage, {
                latitude: this.latitude,
                longitude: this.longitude
              });
            }, function(error) {
              console.log(error);
            })
          })
        }, function(error) {
          console.log(error);
        });
      }
    }

說明:首先app.component.ts檢查是否有任何存儲的信息。 如果有一些信息,則將加載HomePage,否則將加載LoginPage。

現在在構造函數級別的login.ts中 ,正在初始化Facebook對象。 每當調用fbLogin()方法(可能是通過單擊按鈕),Facebook登錄就會發生,並提供您提供的權限數組。 成功登錄后,用戶信息將存儲在設備中,然后加載HomePage(我在推送HomePage時傳遞了一些值,請忽略該信息)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM