首页 > 解决方案 > 如何在 SwiftUI 中正确使用谷歌登录

问题描述

当我尝试登录并在下一个视图上使用 GIDSignIn 注销并导航到上一个视图时,一切都很好,但是当我尝试再次登录时,警报询问应用程序想要使用 google 登录,当我按继续 - 我有一个错误 说:

键盘无法呈现视图控制器(试图呈现)

和下一个错误

第一响应者错误:非键窗口尝试重新加载 - 由于手动键盘而允许(第一响应者窗口是 >,关键窗口是;层 = >)

我的代码

import SwiftUI
import Foundation
import GoogleSignIn

struct LoginView: View {

    @ObservedObject var loginViewModel = LoginViewModel()

    var body: some View {

        NavigationView {
            VStack {

                Button(action: SocialLogin().attemptLoginGoogle, label: {
                    HStack{
                        Image("google")
                        Text("Google login")
                            .font(.title)
                    }
                })
                        .padding(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
                        .background(Color.white)
                        .cornerRadius(8.0)
                        .shadow(radius: 4.0)

                NavigationLink(destination: UserData(), isActive: self.$loginViewModel.isLogedIn) {
                    EmptyView()
                }
            }
            .navigationBarTitle(Text("Login"))
        }

    }
}

struct LoginView_Previews: PreviewProvider {
    static var previews: some View {
        LoginView()
    }
}

struct SocialLogin: UIViewRepresentable {

    func makeUIView(context: UIViewRepresentableContext<SocialLogin>) -> UIView {
        return UIView()
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<SocialLogin>) {
    }

    func attemptLoginGoogle() {

        GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.last?.rootViewController
        GIDSignIn.sharedInstance()?.signIn()

    }
}

标签: iosswiftswiftuigoogle-signin

解决方案


我在 SwiftUI 中遇到了这个问题。

我使用这个代码。

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

推荐阅读