[React Native] Implement GoogleSignIn with Firebase in iOS
2022. 3. 18. 13:20ㆍReact Native/API
1. Create Firebase project in Firebase console
- Apple bundle ID 입력 (Xocode - Show the project navigator - project - General - Identity - Bundle Identifier)
@import UIKit;
@import Firebase;
FirebaseApp.configure()
⬇️
static void InitializeFlipper(UIApplication *application) {
...
}
#endif
@import UIKit;
@import Firebase;
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
#ifdef FB_SONARKIT_ENABLED
InitializeFlipper(application);
#endif
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
...
[FIRApp configure];
return YES;
}
The app is now connected to Firebase.
2. Activate Google Login in Firebase
Firebase Dashboard-> Authentication -> Google Sign-in method -> 사용 설정 toggle
3. Install GoogleSignIn API / Firebase API
[ terminal ] in your project folder
npm install -save @react-native-community/google-signin
npm install --save @react-native-firebase/app
cd ios
pod install
- Set REVERTSED_CLIENT_ID in Xode > project > info > URL Types > + > URL Schemes
4. Get ClientId, OAuth 동의 화면 설정
- Get webClientId, iosClientId Google Cloud Platform > 사용자 인증 정보 > OAuth 2.0 클라이언트 ID
- Configure in here (code)
GoogleSignin.configure({
webClientId: '', // client ID of type WEB for your server (needed to verify user ID and offline access)
iosClientId: '' // [iOS] optional, if you want
});
- OAuth 동의 화면 설정
- 테스트 사용자 > ADD USER에 테스트할 이메일 등록
5. Code
import React, { useState } from 'react';
import {
Button,
Image,
SafeAreaView,
StatusBar,
StyleSheet,
Text,
View
} from 'react-native';
import {
GoogleSignin,
GoogleSigninButton,
statusCodes
} from 'react-native-google-login';
const App = () => {
const [pushData, setPushData] = useState();
const [loggedIn, setLoggedIn] = useState(false);
const [isSignInProgress, setIsSignInProgress] = useState(false);
const [userInfo, setUserInfo] = useState();
const signIn = async () => {
try {
await GoogleSignin.hasPlayServices();
const userInfoFromGoogle = await GoogleSignin.signIn();
console.log(userInfoFromGoogle);
setUserInfo(userInfoFromGoogle);
setLoggedIn(true);
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
// user cancelled the login flow
} else if (error.code === statusCodes.IN_PROGRESS) {
// operation (f.e. sign in) is in progress already
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
// play services not available or outdated
} else {
// some other error happened
}
}
};
const signOut = async () => {
try {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
symbolicateStackTrace({ userInfo: null, loggedIn: false }); //Remember to remove the user from this app's state
} catch (error) {
console.error(error);
}
};
React.useState(() => {
GoogleSignin.configure({
scopes: ['https://www.googleapis.com/auth/drive.readonly'], // what API you want to access on behalf of the user, default is email and profile
webClientId:
'559502922250-cvheetrgmhti559o4m7c6n2sla46ks5o.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
hostedDomain: '', // specifies a hosted domain restriction
loginHint: '', // [iOS] The user's ID, or email address, to be prefilled in the authentication UI if possible. [See docs here](https://developers.google.com/identity/sign-in/ios/api/interface_g_i_d_sign_in.html#a0a68c7504c31ab0b728432565f6e33fd)
forceConsentPrompt: true, // [Android] if you want to show the authorization prompt at each login.
accountName: '', // [Android] specifies an account name on the device that should be used
iosClientId:
'559502922250-rodebni93tivdt7015noe631upb22o1j.apps.googleusercontent.com' // [iOS] optional, if you want
});
});
return (
<SafeAreaView>
<View>
<StatusBar barStyle='dark-content' />
<SafeAreaView>
<View style={styles.sectionContainer}>
<GoogleSigninButton
style={{ width: 192, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={signIn}
disabled={isSignInProgress}
/>
</View>
<View style={styles.buttonContainer}>
{!loggedIn && <Text>You are currently logged out</Text>}
{loggedIn && (
<Button
onPress={signOut}
title='Signout'
color='#841584'
></Button>
)}
</View>
{loggedIn && (
<View>
<View style={styles.listHeader}>
<Text>User Info</Text>
</View>
<View style={styles.dp}>
<Image
style={{ width: 100, height: 100 }}
source={{
uri: userInfo && userInfo.user && userInfo.user.photo
}}
/>
</View>
<View style={styles.detailContainer}>
<Text style={styles.title}>Name</Text>
<Text style={styles.message}>
{userInfo && userInfo.user && userInfo.user.name}
</Text>
</View>
<View style={styles.detailContainer}>
<Text style={styles.title}>Email</Text>
<Text style={styles.message}>
{userInfo && userInfo.user && userInfo.user.email}
</Text>
</View>
<View style={styles.detailContainer}>
<Text style={styles.title}>ID</Text>
<Text style={styles.message}>
{userInfo && userInfo.user && userInfo.user.id}
</Text>
</View>
</View>
)}
</SafeAreaView>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
listHeader: {
backgroundColor: '#eee',
color: '#222',
height: 44,
padding: 12
},
detailContainer: {
paddingHorizontal: 20
},
title: {
fontSize: 18,
fontWeight: 'bold',
paddingTop: 10
},
message: {
fontSize: 14,
paddingBottom: 15,
borderBottomColor: '#ccc',
borderBottomWidth: 1
},
dp: {
marginTop: 32,
paddingHorizontal: 24,
flexDirection: 'row',
justifyContent: 'center'
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
flexDirection: 'row',
justifyContent: 'center'
},
buttonContainer: {
marginTop: 32,
paddingHorizontal: 24,
flexDirection: 'row',
justifyContent: 'center'
}
});
export default App;
5. Result log
{ idToken: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
scopes:
[ 'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'openid',
'https://www.googleapis.com/auth/drive.readonly' ],
user:
{ photo: 'https://lh3.googleusercontent.com/a/XXXXXXX',
givenName: 'X',
familyName: 'XX',
name: 'XXX',
email: 'XXX@gmail.com',
id: '100XXXXXXXXXXXXXXX' } }