简体   繁体   English

使用 React Native 实现 Google+ 登录

[英]Implement Google+ Sign-In with React Native

I'm wanting to integrate G+ Sign In (as per https://developers.google.com/+/mobile/ios/sign-in ) in a React Native app.我想在 React Native 应用程序中集成 G+ 登录(根据https://developers.google.com/+/mobile/ios/sign-in )。 I have Facebook Sign In working via http://brentvatne.ca/facebook-login-with-react-native/ which is working perfectly, but I'm not sure what to do at this point of the G+ docs:我通过http://brentvatne.ca/facebook-login-with-react-native/使用 Facebook 登录,它运行良好,但我不知道在 G+ 文档的这一点上该怎么做:

In your view controller's .h file, import GooglePlus/GooglePlus.h, and declare that this controller class implements the GPPSignInDelegate protocol在视图控制器的 .h 文件中,导入 GooglePlus/GooglePlus.h,并声明该控制器类实现 GPPSignInDelegate 协议

If anyone could provide some pointers/code samples?如果有人可以提供一些指针/代码示例?

Thanks!谢谢!

EDIT 2017编辑 2017

Within the Expo framework, which is now the default for react-native apps, there is built in Google Authentication available:在 Expo 框架(现在是 react-native 应用程序的默认设置)中,内置了可用的 Google 身份验证:

Expo documentation: https://docs.expo.io/versions/latest/sdk/google.html世博会文档: https : //docs.expo.io/versions/latest/sdk/google.html

Get Android and iOS client ids: https://console.developers.google.com/apis/credentials获取 Android 和 iOS 客户端 ID: https : //console.developers.google.com/apis/credentials

import React from 'react'
import Expo from 'expo'
import Button from 'react-native-button'

class Login extends React.Component {
  signInWithGoogleAsync = async () => {
    try {
      const result = await Expo.Google.logInAsync({
        androidClientId: process.env.GOOGLE_ANDROID_CLIENT_ID,
        iosClientId: process.env.GOOGLE_IOS_CLIENT_ID,
        scopes: ['profile'],
      })

      if (result.type === 'success') {
        return result
      }
      return { cancelled: true }
    } catch (e) {
      return { error: e }
    }
  }


  onLoginPress = async () => {
    const result = await this.signInWithGoogleAsync()
    // if there is no result.error or result.cancelled, the user is logged in
    // do something with the result
  }

  render() {
    return (<Button onPress={this.onLoginPress}>Login</Button>)
  }
}

OLD ANSWER旧答案

There is now a library for signing in with Google+ for react-native: https://github.com/devfd/react-native-google-signin现在有一个用于使用 Google+ 登录 react-native 的库: https : //github.com/devfd/react-native-google-signin

So this is only semi-related to React Native, since your main issue seems to be writing the Obj-C side of the G+ sign in. To that end, grab the iOS Quick Start app for Google Plus:所以这只是与 React Native 半相关,因为您的主要问题似乎是编写 G+ 登录的 Obj-C 端。为此,获取适用于 Google Plus 的 iOS 快速入门应用程序:

https://developers.google.com/+/quickstart/ios https://developers.google.com/+/quickstart/ios

Follow the instructions to open the sample project and you'll find the SignInViewController.m file which contains this line:按照说明打开示例项目,您将找到包含以下行的 SignInViewController.m 文件:

@interface SignInViewController () <GPPSignInDelegate>

That appears to be what you're after.这似乎是你所追求的。

Once you have that working, you'll need to implement the connection to React Native.一旦你开始工作,你就需要实现与 React Native 的连接。 The Facebook post you linked to shows how to do that, but the official documentation is here:您链接到的 Facebook 帖子显示了如何做到这一点,但官方文档在这里:

http://facebook.github.io/react-native/docs/nativemodulesios.html#content http://facebook.github.io/react-native/docs/nativemodulesios.html#content

I also wrote a post to show the simplest Native Module I could think of, which I think describes the general concept pretty well:我还写了一篇文章来展示我能想到的最简单的 Native Module,我认为它很好地描述了一般概念:

http://colinramsay.co.uk/2015/03/27/react-native-simple-native-module.html http://colinramsay.co.uk/2015/03/27/react-native-simple-native-module.html

After so much struggle I have gone through all the issues we face with Google+ signin integration in React Native app.经过这么多的努力,我已经解决了我们在 React Native 应用程序中集成 Google+ 登录所面临的所有问题。 Kindly find a step by step changes need to be done 1. Create Project in Google Cloud Platform : Try free trail I am using google cloud platform, if you are not using that, you just enable apis under google console请找到需要逐步更改的步骤 1. 在 Google Cloud Platform 中创建项目:尝试免费试用我使用的是 Google Cloud Platform,如果您不使用它,则只需在 Google 控制台下启用 apis

  1. Enable Google+ API for your project and generate API Key in your google cloud console为您的项目启用 Google+ API 并在您的 google 云控制台中生成 API Key

  2. Set YourSHA-1 key and package name (as given in AndroidManifest.xml ) of your android project ( Note: if you are using expo for this, then you should eject expo first to achieve this, Read How To Eject Expo )设置您的 android 项目的 YourSHA-1 密钥和包名称(在 AndroidManifest.xml 中给出)(注意:如果您为此使用 expo,那么您应该先弹出 expo 以实现此目的, 阅读如何弹出 Expo

To generate your own SHA-1 use the command -> keytool -list -v -keystore mystore.keystore要生成您自己的 SHA-1,请使用命令 -> keytool -list -v -keystore mystore.keystore

NOTE : If Your build is debug build then theSHA-1 generated with above command won't work, kindly check your adb logs carefully, theSHA-1 being used by your android debug build will be logged in the device log.注意:如果您的构建是调试构建,那么使用上述命令生成的 SHA-1 将不起作用,请仔细检查您的 adb 日志,您的 android 调试构建使用的 SHA-1 将记录在设备日志中。 To check device log run the below command from your /Users//Library/Android/sdk/platform-tools —> adb logcat要检查设备日志,请从您的 /Users//Library/Android/sdk/platform-tools —> adb logcat 运行以下命令

  1. Import the same project in firebase : If you are not using firebase then skip this step and next step在 firebase 中导入相同的项目:如果您不使用 firebase,请跳过此步骤和下一步

  2. Setup android project in your firebase project, then setup authentication methods being used in your app.在您的 firebase 项目中设置 android 项目,然后设置您的应用程序中使用的身份验证方法。

  3. Then setup sameSHA-1 Key for your firebase project: Navigate to Project setting from side bar and click on general , select android app and set SHA-1 key然后为您的 Firebase 项目设置相同的 SHA-1 密钥:从侧边栏导航到项目设置并单击常规,选择 android 应用程序并设置 SHA-1 密钥

NOTE: Once SHA-1 is setup, download google-services.json file in the same page.注意:设置 SHA-1 后,在同一页面中下载 google-services.json 文件。 and keep the file under your android project director app folder /ReactNativeProjectFolder/android/app并将文件保存在您的 android 项目主管 app 文件夹 /ReactNativeProjectFolder/android/app 下

  1. add 'react-native-google-signin' and 'firebase' modules添加“react-native-google-signin”和“firebase”模块

npm install react-native-google-signin –save npm install react-native-google-signin –save

npm install firebase –save npm install firebase –save

  1. Add dependency in your /app/bundle.gradle在您的 /app/bundle.gradle 中添加依赖项

Note : in below code those excludes are most important, or else you will encounter strange linking errors.注意:在下面的代码中,那些排除是最重要的,否则你会遇到奇怪的链接错误。

implementation project(':react-native-google-signin')

if your app is using some other dependencies like react-native-maps or react-native-social-share then do below changes as well如果您的应用程序正在使用其他一些依赖项,例如 react-native-maps 或 react-native-social-share,那么也进行以下更改

implementation(project(":react-native-google-signin")){
    exclude group: "com.google.android.gms" // very important
}
compile(project(':react-native-maps')) {
      exclude group: 'com.google.android.gms', module: 'play-services-base'
      exclude group: 'com.google.android.gms', module: 'play-services-maps'
    }
implementation 'com.google.android.gms:play-services-base:11.+'
implementation 'com.google.android.gms:play-services-maps:11.+'
  1. your android/bundle.gradle file should look as follows // Top-level build file where you can add configuration options common to all sub-projects/modules.您的 android/bundle.gradle 文件应如下所示 // 顶级构建文件,您可以在其中添加所有子项目/模块通用的配置选项。

    buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' classpath 'com.google.gms:google-services:3.0.0' // <--- add this // NOTE: Do not place your application dependencies here; buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' classpath 'com.google.gms:google-services:3.0.0' // <-- - 添加此 // 注意:不要将您的应用程序依赖项放在此处; they belong // in the individual module build.gradle files } }它们属于 // 在单独的模块 build.gradle 文件中 } }

    allprojects { repositories { mavenLocal() jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } } } allprojects { repositories { mavenLocal() jcenter() maven { // 所有 React Native(JS、Obj-C 源代码、Android 二进制文件)都是从 npm url "$rootDir/../node_modules/react-native/android" 安装的 } } }

    ext { compileSdkVersion = 23 targetSdkVersion = 23 buildToolsVersion = "23.0.1" googlePlayServicesVersion = "10.2.4" androidMapsUtilsVersion = "0.5+" } ext { compileSdkVersion = 23 targetSdkVersion = 23 buildToolsVersion = "23.0.1" googlePlayServicesVersion = "10.2.4" androidMapsUtilsVersion = "0.5+" }

  2. un below commands un 下面的命令

npm install安装

react-native link反应原生链接

  1. Once you run react native link – check android/settings.gradle file , cross check that there should not be duplicate lines of content.一旦你运行 react native link - 检查 android/settings.gradle 文件,交叉检查不应该有重复的内容行。

So far we have done project level configurations, now let us see code changes至此我们已经完成了项目级别的配置,现在让我们看看代码的变化

  1. React Native Google sign-in/sign-up using firebase code使用 Firebase 代码 React Native Google 登录/注册

    import { GoogleSignin } from 'react-native-google-signin';从'react-native-google-signin'导入{ GoogleSignin}; import firebase from 'firebase';从'firebase'导入firebase;

    function googleAuthConfig(successCallback, failureCallback) { GoogleSignin.configure({ iosClientId: CLIENT_IDS.GOOGLE_IOS_CLIENT_ID, webClientId: '', hostedDomain: '', forceConsentPrompt: true, accountName: '' }) .then(() => { console.log('Google Config Success'); successCallback(); }) .catch((err) => { console.log('Google Config Error'); failureCallback(err); }); function googleAuthConfig(successCallback, failureCallback) { GoogleSignin.configure({ iosClientId: CLIENT_IDS.GOOGLE_IOS_CLIENT_ID, webClientId: '', hostsDomain: '', forceConsentPrompt: true, accountName: '' }) .then(() => { console.log ('Google 配置成功'); successCallback(); }) .catch((err) => { console.log('Google Config Error'); failureCallback(err); }); } }

    function googleSignin() { googleAuthConfig(() => { GoogleSignin.signIn() .then((user) => { const { accessToken } = user; var credentials = firebase.auth.GoogleAuthProvider.credential(null, accessToken); firebase.auth().signInWithCredential(credentials) .then((firebaseResult) => { loginToSG(dispatch, firebaseResult, props, 'Google', registerCallback); }) .catch(error => console.log('error while checking with firebase', error)); }) .catch((err) => { console.log(err); }); }, (googleConfigErr) => { console.log(googleConfigErr); });函数 googleSignin() { googleAuthConfig(()​​ => { GoogleSignin.signIn() .then((user) => { const { accessToken } = user; var credentials = firebase.auth.GoogleAuthProvider.credential(null, accessToken); firebase .auth().signInWithCredential(credentials) .then((firebaseResult) => { loginToSG(dispatch, firebaseResult, props, 'Google', registerCallback); }) .catch(error => console.log('error while check with firebase', error)); }) .catch((err) => { console.log(err); }); }, (googleConfigErr) => { console.log(googleConfigErr); }); } }

  2. Finally the most important step is -> once do npm cache clean, delete your existing app from device, delete build folders then run the app最后最重要的一步是 -> 一旦清理 npm 缓存,从设备中删除现有的应用程序,删除构建文件夹然后运行应用程序

react-native run-android react-native run-android

Credits : Step by step guide with screenshots and code snippets积分: 带有屏幕截图和代码片段的分步指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM