Как правильно использовать Google SignIn с SwiftUI - PullRequest
0 голосов
/ 14 января 2020

Когда я пытаюсь войти и при следующем просмотре выйти с помощью GIDSignIn и перейти к предыдущему представлению, все в порядке, но когда я пытаюсь войти снова, появляется запрос Приложение хочет использовать Google войти в , когда я нажимаю продолжить - у меня появляется сообщение об ошибке:

Клавиатура не может представить контроллеры представления (попытка представить)

и следующая ошибка

Ошибка первого респондента: попытка перезагрузки неключевого окна - разрешение из-за ручной клавиатуры (окно первого респондента>, окно ключа; layer =>)

My код

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()

    }
}

1 Ответ

1 голос
/ 15 января 2020

Таким образом, проблема была в

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

Вы должны представить в ViewController (в моем случае сработал UIRepresentableViewController), иначе он скажет вам, что клавиатура не может показать или представить новый View

Wrapper:

struct WrapedViewController: UIViewControllerRepresentable {

    func makeUIViewController(context: Context) -> LoginViewController {
        let vc =  LoginViewController()
        print("\nmakeUIViewController \(vc)")
        return vc
    }

    func updateUIViewController(_ uiViewController: LoginViewController, context: Context) {
        print("updateUIViewController \(uiViewController)")
    }

    static func dismantleUIViewController(_ uiViewController: LoginViewController, coordinator: Self.Coordinator) {
        print("dismantleUIViewController \(uiViewController)")
    }
}

Контроллер Wraped View:

class LoginViewController: UIViewController {

    override func viewDidLoad() {

        let screenWidth = self.view.frame.size.width
        let screenHeight = self.view.frame.size.height

        let height: CGFloat = 40.0
        let width: CGFloat  = 120.0

        let button = UIButton(frame: CGRect(x: (screenWidth / 2.0) - (width / 2.0),
                                            y: (screenHeight / 2.0) - (height / 2.0),
                                            width: width,
                                            height: height))

        button.backgroundColor = .green
        button.setTitle("Test Button", for: .normal)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        self.view.addSubview(button)
    }

    @objc func buttonAction(sender: UIButton!) {
        GIDSignIn.sharedInstance()?.presentingViewController = self
        GIDSignIn.sharedInstance()?.signIn()
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...