SwiftUI macOS应用中如何替换Google登录的rootViewController?
在SwiftUI macOS应用中集成Google登录的正确方式
你代码中的核心问题
你之前的尝试存在两处关键错误:
- 错误地将
connectedScenes.first强转为NSWindow,正确类型应为NSWindowScene - macOS版本的
signIn方法需要传入NSWindow类型的presentingWindow参数,而非NSViewController
正确实现代码
以下是SwiftUI macOS中Google登录的完整可行代码:
GoogleSignInButton { // 获取当前应用的主窗口 guard let windowScene = NSApplication.shared.connectedScenes.first as? NSWindowScene, let presentingWindow = windowScene.windows.first else { print("无法获取主窗口") return } // 初始化Google登录配置 let signInConfig = GIDConfiguration(clientID: "你的Google客户端ID") // 调用macOS专属的登录方法 GIDSignIn.sharedInstance.signIn(with: signInConfig, presentingWindow: presentingWindow) { user, error in // 处理错误 if let error = error { print("登录失败: \(error.localizedDescription)") return } // 登录成功,处理用户信息 guard let user = user else { return } let userId = user.userID ?? "未知ID" let userName = user.profile?.name ?? "未知名称" print("登录成功: \(userName) (\(userId))") // 此处跳转至应用主内容界面 } }
关键注意事项
- 应用签名要求:必须使用开发者证书签名应用,否则Keychain无法存储登录凭据,会导致登录后无法持久化会话或重复授权
- 客户端ID配置:在Google Cloud控制台中,需单独为macOS应用创建客户端ID,不要复用iOS的ID
- Info.plist配置:需添加对应的URL Scheme,格式为
com.googleusercontent.apps.你的客户端ID,确保登录回调能正确跳转回应用
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

