2024. 3. 3. 19:20ㆍ🍏/Swift
- Firebase 를 시작하여 프로젝트 만들기
- 앱에 Firebase를 추가하여 시작하기 (bundle id, nickname 등록)
- 구성 파일 다운로드(Google OAuth 사용자는 굳이 다운로드 안해도됨. 잠시 뒤에 credentials가 포함된 구성파일을 준다.)
- Upload 해도되는가에 대해서 찾아봤는데, 뭐 중요한 내용은 없다고 한다. (https://groups.google.com/g/firebase-talk/c/EEEwttbpPJU)
그래도 저라면 안 올릴 것 같습니다.
- Package Dependency 추가 https://github.com/firebase/firebase-ios-sdk
- Appdelegate에 코드 추가
코드 보기
import UIKit import FirebaseCore @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() return true } }
여기까지가 Firebase 기본 설정.
아래부터 로그인 연동과정
- 제품 카테고리의 빌드 > Authentication > 추가 제공업체 > Google
- 우측키로 사용설정후 최신 구성파일 다운로드
- 기존 GoogleService-Info와 동일하지만 credentials가 존재하는 최신 구성파일을 받을 수 있음.
- TARGETS > Info > URL Types > URL Schemes에 REVERSED_CLIENT_ID의 value값 추가.
com.googleusercontent.apps.921929828930-bvgm52ekdqaen97lj00malabcdefghijk
대충 이렇게 생겼음. - 인증 리디렉션 URL 처리
코드 보기App delegate 같은 이름의 함수가 있을텐데 그걸 이걸로 덮어 씌우면됨.
func application( _ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:] ) -> Bool { var handled: Bool handled = GIDSignIn.sharedInstance.handle(url) if handled { return true } // Handle other custom URL types. // If not handled by this app, return false. return false } - 사용자의 로그인 상태 복원 시도
코드 보기
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() // 이미 추가 된줄. // 아래부터가 로그인 상태 복원 줄 GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in if error != nil || user == nil { // Show the app's signed-out state. } else { // Show the app's signed-in state. } } return true } - https://console.cloud.google.com/ 콘솔 클라우드 구글에서 OAuth 클라이언트 ID 인증정보를 만든후
- GIDClientID 등록 (info.plist)
이미지 보기
iOS OAuth client 클라이언트 ID 값 넣어주면됨
- 그럼 이제 UIKit에서 버튼 넣고 호출해주기만 하면됨
코드 보기@IBAction func signIn(sender: Any) { GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in guard error == nil else { return } // If sign in succeeded, display the app's main content View. } } - 여기까지 하면 로그인 GIDSignIn이 에러를 뱉지 않았다는 뜻이니까 로그인에 성공한 것이고, 거의 다왔음.
로그인 이미지 보기로그인 버튼 - 이제 해당 계정을 내 프로젝트의 firebase와 연동시켜 줘야하는 코드가 필요함
Firebase 연동 코드
@IBAction func signIn(sender: Any) { // 먼저 clientID를 검사하고 GIDConfiguration을 설정 guard let clientID = FirebaseApp.app()?.options.clientID else { return } // Google SignIn configuration object 생성 let config = GIDConfiguration(clientID: clientID) GIDSignIn.sharedInstance.configuration = config // 이제 Google Sign-In 과정을 시작합니다. GIDSignIn.sharedInstance.signIn(withPresenting: self) { [unowned self] result, error in guard error == nil else { return } guard let user = result?.user, let idToken = user.idToken?.tokenString else { return } let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: user.accessToken.tokenString) Auth.auth().signIn(with: credential) { result, error in // 여기에서 유저가 내 firebase앱에 signin함. guard error == nil else { // 인증 과정에서 에러처리 부분 print("Firebase 인증 에러: \(error!.localizedDescription)") return } // 여기서 사용자가 성공적으로 로그인 처리 print("Firebase를 통한 인증 성공") } } } - 로그아웃
로그아웃 코드
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) } - 버튼 키 google 버튼 양식대로 변경
버튼 예시 코드
https://developers.google.com/identity/sign-in/ios/reference/Enums?authuser=0
구글에서 지원하는 googlesignin framework reference
lazy var signInButton: GIDSignInButton = { let button = GIDSignInButton() button.style = .wide button.style = .standard button.style = .iconOnly button.colorScheme = .dark button.colorScheme = .light button.addTarget(self, action: #selector(signIn), for: .touchUpInside) return button }()
로그인에 완료되면 Firebase 의 Authentication 해당 유저가 등록이 됩니다! 끝!

GoogleSignIn Framework Reference | Authentication | Google for Developers
Send feedback GoogleSignIn Framework Reference Stay organized with collections Save and categorize content based on your preferences. Enumerations The following enumerations are available globally. A list of potential error codes returned from the Google S
developers.google.com
클라이언트 인증 | Google Play services | Google for Developers
이 페이지는 Cloud Translation API를 통해 번역되었습니다. 클라이언트 인증 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 특정 Google Play 서비스 (예: Google 로그
developers.google.com
'🍏 > Swift' 카테고리의 다른 글
[Swift] Tail Call Optimization / TCO / 꼬리재귀 (0) | 2024.03.16 |
---|---|
[Swift] Metadata (0) | 2024.03.14 |
[Extension] ShareExtension에서 Containing App을 여는 방법 (0) | 2024.02.20 |
[Framework] Static / Dynamic / 실전, 응용 (0) | 2024.02.19 |
[Swift] Dynamic Libraries or Static Libraries / 동적 라이브러리, 정적라이브러리 (2) | 2024.02.08 |