https://firebase.google.com/docs/auth/ios/google-signin?hl=ko 를 참조하여 구글 로그인 연동을 해보았다.
사이트를 들어가보면
--
시작하기 전에
- Apple 프로젝트에 Firebase를 추가합니다. Podfile에 다음 포드를 추가합니다.
pod 'FirebaseAuth' pod 'GoogleSignIn'
- 아직 Firebase 프로젝트에 앱을 연결하지 않았다면 Firebase Console에서 연결합니다.
- Firebase Console에서 Google을 로그인 방법으로 사용 설정합니다.
- Firebase Console에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 Google 로그인 방법을 사용 설정하고 저장을 클릭합니다.
----
이라고 뜬다. cocoapod가 아닌 add package를 이용하려하는 나에게 곤란한 상황이였다.
시작대로 하려니 위와같은 오류가 발생했다. Googlesignin 모듈이 없으니 찾아야지 뭐.
https://swiftpackageregistry.com/google/GoogleSignIn-iOS
GoogleSignIn - Swift Package Registry
swiftpackageregistry.com
구글에 검색하니 위 사이트에서
- Using Swift Package Manager:
git clone https://github.com/google/GoogleSignIn-iOS
open GoogleSignIn-iOS/Samples/ObjC/SignInSample/SignInSample.xcodeproj
If you would like to see a Swift example, take a look at Samples/Swift/DaysUntilBirthday.
의 clone ~~ -ios 부분을 선택해 검색하니 singnin의 오류가 발생하지 않게 되었다.
-
여기까지 하고 swiftui로 계속해서 해보려 햇지만 실패햇다. cocoapod가 마음 편할듯
---
2주넘게 헤맨결과 드디어 해내게되었다.
signin button 은 구현하는데 성공하였으나 버튼을 눌럿을때 아무반응도 없었다.
<오류코드>
@IBOutlet weak var btn: GIDSignInButton!
override func viewDidLoad() {
super.viewDidLoad()
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
guard let clientID = FirebaseApp.app()?.options.clientID else { return }
// Create Google Sign In configuration object.
let config = GIDConfiguration(clientID: clientID)
// Start the sign in flow!
GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in
if let error = error {
// ...
return
}
guard
let authentication = user?.authentication,
let idToken = authentication.idToken
else {
return
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken,
accessToken: authentication.accessToken)
Auth.auth().signIn(with: credential) { result, error in
if let error = error {
print(error)
}
} } }
}
처음에 오류가나서 2주동안 해멧던 코드이다. 인터넷에 자료가 많지않아 한참을 해메었다.
Break Point를 찍어보니 guard let authentication = user ~~~~ 부분부터 막히게 되었다.
해결법을 찾아보았다.
첫번째 의심점은 action으로 연결이 되어있지 않다는 점이였다.
처음에 action에 연결된점이 Touch up inside 가 아닌 value change로 연결되어있었다.
액션 연결을 옮겨보고 print 를 찍어보니 정상적으로 찍히는것을 볼 수 있었다.
이후에도 오류가 낫다. 액션함수안에 동작을 하는 행위들이 있어야 하는것은 알겟는데 무엇이 문제인지 모르겟다.
브레이크 포인트를 걸어보았알때 47번이후에 라인 이후에 브포가 튕긴다. 아래에 오류문을 선언했음에도 튕기는것을 보면 받아오는 값이 튕기는것을 확인할 수 있었다.
이 페이지가 1초정도 뜨고 바로 signin 애뮬레이터가 돌아가는데 당최 이유를 모르겟다.
아래는 해답이다
viewcontroller에서 viewdidload를 닫고 아래에 함수로 선언해주니 되게되었다.
//
// ViewController.swift
// sign
//
// Created by 이지훈 on 2022/07/12.
//
import UIKit
import FirebaseCore
import GoogleSignIn
import FirebaseAuth
class ViewController: UIViewController {
@IBOutlet weak var signInButton: GIDSignInButton!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func googleLoginButton(_ sender: Any) {
guard let clientID = FirebaseApp.app()?.options.clientID else { return }
// Create Google Sign In configuration object.
let config = GIDConfiguration(clientID: clientID)
// Start the sign in flow!
GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in
if let error = error {
print(error)
return
}
guard
let authentication = user?.authentication,
let idToken = authentication.idToken
else {
return
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken,
accessToken: authentication.accessToken)
Auth.auth().signIn(with: credential) { result, error in
if let error = error {
print(error)
}
}
}
//
// func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
// return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
// }
//
// func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
// }
// }
//
// }
}}
override 를 끝까지 열어두면 ibaction을 fun함수를 바꾸라고 나오기때문에 오버라이드를 didload로만 닫아두고 아래에 구글문서를 작성한다.
swift를 공부한지 얼마 되지않아 생긴 멍청한 실수였엇다
'IOS - Swift' 카테고리의 다른 글
Swift 기초문법 - 시작하기 (0) | 2022.09.12 |
---|---|
swift 기초문법 정리 - 조건문 (0) | 2022.08.27 |
[ios/swift] firebase 연결 (0) | 2022.07.02 |
ios스터디-sns개발-4주차 (0) | 2022.07.02 |
ios 스터디-sns개발-3주차 (0) | 2022.07.02 |