首页 > 解决方案 > 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 中的信息,但我不明白如何使用它。有人可以帮我吗?

标签: swiftswiftuigame-centergamekituiviewcontrollerrepresentable

解决方案


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>) {
        
    }
    
}

推荐阅读