swift - SwiftUI Game Center 身份验证不提示用户登录
问题描述
我有以下代码在我的 SwiftUI 应用程序中对 Game Center 中的本地玩家进行身份验证。如果玩家尚未登录,我希望 Game Center 提示用户登录,但这不会发生。
class AppSettings: UINavigationController {
func authenticateUser() {
let localPlayer = GKLocalPlayer.local
localPlayer.authenticateHandler = { vc, error in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
}
}
}
可能是什么问题呢?我还阅读了有关在课堂上的某处使用 UIViewControllerRepresentable 将 UIKit 的 ViewController 集成到 SwiftUI 中的信息,但我不明白如何使用它。有人可以帮我吗?
解决方案
I didn't get anyone to answer my question correctly and after days of digging I found a solution. So I had to use the UIKit implementation like below and create a wrapper around it using UIViewControllerRepresentable in the GameCenterManager Struct. After that all I had to do was call GameCenterManager() inside my SwiftUI view in a ZStack and the job is done!
import SwiftUI
import UIKit
import GameKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
authenticateUser()
}
let localPlayer = GKLocalPlayer.local
func authenticateUser() {
localPlayer.authenticateHandler = { vc, error in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
if vc != nil {
self.present(vc!, animated: true, completion: nil)
}
if #available(iOS 14.0, *) {
GKAccessPoint.shared.location = .bottomLeading
GKAccessPoint.shared.showHighlights = true
GKAccessPoint.shared.isActive = self.localPlayer.isAuthenticated
// Fallback on earlier versions
}
}
}
}
struct GameCenterManager: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<GameCenterManager>) -> ViewController {
let viewController = ViewController()
return viewController
}
func updateUIViewController(_ uiViewController: ViewController, context: UIViewControllerRepresentableContext<GameCenterManager>) {
}
}
推荐阅读
- laravel - 注册后 Laravel Auth 用户并重定向到特定 URL
- mysql - 使用另一个表中的选择总和更新表
- groovy - 循环在 Groovy 脚本中无法正确执行
- ruby-on-rails - 如何将整数转换为货币并显示正确的美分
- python - 球体上 2 点之间平均距离的期望值的偏差
- vue.js - 默认为每个 Vue 实例加载插件
- ruby-on-rails - 如何为 ruby 2.7.1 解决 AWS Elastic Beanstalk 上的 Rail 6 部署错误
- installation - 使用 cargo 安装 deno 时“找不到名为 `map_or` 的方法”
- r - sh 权限在exams2pdf 中被拒绝
- django - Heroku 不断更改我的 heroku-redis 插件的 url