Max Webb
Max Webb

Reputation: 152

Google Auth with Firebase in Swift without using storyboards

I am trying to get my application to sign in with Google using a function and without using Google's pre built button, but using GIDSignIn.sharedInstance().signIn(). However, it is wanting to set the view first but I can't as I am using SwiftUI without Storyboards.

I have defined a gLog() function in a class called auth() stored as authC, I then call authC.gLog() upon pressing a button in my view, however it has a thread issue and responds with this error here: Thread 1: "presentingViewController must be set."

View File (SwiftUI):

//
//  ContentView.swift
//  maraki-rev1
//
//  Created by Max Webb on 25/10/20.
//

import SwiftUI
// base page name
var pageName: String = "Welcome"
var authC = auth()

struct ContentView: View {
    var body: some View {
        VStack{
            Text(verbatim: data.userFirst)
                .font(.title)
                .multilineTextAlignment(.center)
            Text("Please Log In Below")
                .padding()
            HStack{
                Button(action: {
                    authC.gLog()
                }) {
                Text("Log In with Google")
                    .padding()
            }
                Button(action: {
                    authC.aLog()
                }) {
                Text("Log In with Apple")
                    .padding()
            }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Class File that contains glog() and the auth() class.

//
//  authContent.swift
//  maraki-rev1
//
//  Created by Max Webb on 26/10/20.
//

import Foundation
import Firebase
import GoogleSignIn
import SwiftUI
class auth {
    // google auth login
    func gLog(){
        GIDSignIn.sharedInstance().signIn()

    }
    func aLog(){
        print("hello with apple")
    }
}

There is nothing else on line that can help and their are a lack of tutorials surrounding my issue, so I appreciate all answers and comments on this question.

Thanks once again, Max.

Upvotes: 0

Views: 261

Answers (1)

Max Webb
Max Webb

Reputation: 152

Okay so found a solution to this issue in the end, posting to help other people as this has given me a headache for the past 3 hours!

Including this code into my gLog() function lets the application open the Google prompt to log in.

if(GIDSignIn.sharedInstance()?.presentingViewController == nil){
    GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.last?.rootViewController
}
GIDSignIn.sharedInstance()?.signIn()

Found this answer (including the above code snippet) on this question here: How to properly use google signIn with SwiftUI - credit to https://stackoverflow.com/users/3961296/joshua-pogi-28

Upvotes: 1

Related Questions