如何在 SwiftUi 中将 rootViewController 传递给 Google 登录?

Fra*_*ank 6 google-signin rootviewcontroller swiftui

这是我多年来找到我需要的每个答案后的第一个问题。

\n

我在 IOS 中为 iPhone 编写了一些应用程序,我并不总是确定我在做什么,但它们可以工作!

\n

他们使用 Google 登录,并且工作正常。\n现在我想为 Mac OS 编写一个应用程序,但我无法解决的问题是这一行:

\n
GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController) \n
Run Code Online (Sandbox Code Playgroud)\n

在这个函数中:

\n
func handleSignInButton() {\n\xc2\xa0 GIDSignIn.sharedInstance.signIn(\n\xc2\xa0 \xc2\xa0 withPresenting: rootViewController) { signInResult, error in\n\xc2\xa0 \xc2\xa0 \xc2\xa0 guard let result = signInResult else {\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 // Inspect error\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 return\n\xc2\xa0 \xc2\xa0 \xc2\xa0 }\n\xc2\xa0 \xc2\xa0 \xc2\xa0 // If sign in succeeded, display the app\'s main content View.\n\xc2\xa0 \xc2\xa0 }\n\xc2\xa0 )\n}\n
Run Code Online (Sandbox Code Playgroud)\n

在 Google 登录教程中:\n https://developers.google.com/identity/sign-in/ios/sign-in

\n

我可以用什么来替换 Mac OS 应用程序中的 rootViewController?

\n

我已经尝试过类似的方法,但我有点迷失:

\n
GoogleSignInButton {\nguard let presentingViewController = (NSApplication.shared.connectedScenes.first as? NSWindow)?.windows.first?.NSViewController else {return}\n               \n            let signInConfig = GIDConfiguration.init(clientID: XXXXXXXXX")\n             GIDSignIn.sharedInstance.signIn(\n               with: signInConfig,\n               presentingWindow: presentingViewController) { user, error in\n                 // check `error`; do something with `user`\n             }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

他们在https://github.com/google/GoogleSignIn-iOS上提供建议

\n

Google Sign-In 允许您的用户使用其 Google 帐户和默认浏览器登录您的本机 macOS 应用。在针对 macOS 进行构建时,signInWithConfiguration: 和 addScopes: 方法采用presentingWindow: 参数代替presentingViewController:。请注意,为了让您的 macOS 应用程序通过 macOS 上的钥匙串存储凭据,您需要对您的应用程序进行签名。

\n

有人通过 SwiftUI 使用 Google 登录 Mac OS 应用吗?

\n

Hal*_*ler 4

我还没有对此进行测试,但在2021 年 11 月编写的https://paulallies.medium.com/google-sign-in-swiftui-2909e01ea4ed上,我发现:

guard let presentingViewController = (UIApplication.shared.connectedScenes.first
          as? UIWindowScene)?.windows.first?.rootViewController
      else {return}
Run Code Online (Sandbox Code Playgroud)

first我对拍摄所有场景没有 100% 的信心。如果您的应用支持多个场景,您可能需要考虑不是第一个。

我看到https://github.com/WesCSK/SwiftUI-Firebase-Authenticate-Using-Google-Sign-In中使用了另一种方法。该示例使用旧式UIApplicationDelegate方法,如果您不使用较新的 SwiftUI 应用程序生命周期,可能更容易适应。当然,这是一个 iOS 应用程序,但应用程序委托逻辑应该与您的 Mac 项目类似。