I want to sign in to google according to the method found in this URL:
https://paulallies.medium.com/google-sign-in-swiftui-2909e01ea4ed
but the problem is that App delegate is not found in swiftui new project ? since the app delegate requires client ID implementation as shown in URL
any idea and thanks
CodePudding user response:
This is for everyone having problem with AppDelegate SwiftUI 3.0 new update
Add in app view
import Foundation
import SwiftUI
import Firebase
import GoogleSignIn
@main
struct YourApp: App {
let persistenceController = PersistenceController.shared
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any])
-> Bool {
return GIDSignIn.sharedInstance.handle(url)
}
}
Then in loginView add inside login struct
@State var isLoading : Bool = false
func handleLogin(){
// google sign in
guard let clientID = FirebaseApp.app()?.options.clientID else { return }
// Create Google Sign In configuration object.
let config = GIDConfiguration(clientID: clientID)
isLoading = true
GIDSignIn.sharedInstance.signIn(with: config, presenting: getRootViewController()) { [self] user, error in
if let error = error {
isLoading = false
print(error.localizedDescription)
return
}
guard
let authentication = user?.authentication,
let idToken = authentication.idToken
else {
isLoading = false
return
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: authentication.accessToken)
// Firebase Authentication
Auth.auth().signIn(with: credential) {result, err in
isLoading = false
if let error = error {
print(error.localizedDescription)
return
}
//Displaying User Name...
guard let user = result?.user else {
return
}
print(user.displayName ?? "Success" )
//updating user as logged in
withAnimation{
log_Status = true
// and this is where you want the user to go if successful
goHome()
}
}
}
}
also add this to loginView but as extension
extension View{
func getRect()->CGRect{
return UIScreen.main.bounds
}
// retrieve RootView
func getRootViewController()->UIViewController{
guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
return . init()
}
guard let root = screen.windows.first?.rootViewController else {
return .init()
}
return root
}
}
don't forget to give the button the handleLogin()
Button(action: {handleLogin()}) {
Image("Gmail")
}
.padding()
.foregroundColor(.white)
.background(Color.white)
.cornerRadius(.infinity)
and you are good to go my friends