xcode 如何使用SwiftUI显示Game Center排行榜

fzsnzjdm  于 2022-12-14  发布在  Swift
关注(0)|答案(3)|浏览(193)

我创建了一个测试应用程序来测试将Game Center排行榜添加到我正在创建的一个简单的SwiftUI游戏中。我一直无法弄清楚如何显示Game Center排行榜上的所有分数。
我创建了一个包含Game Center所有功能的类(验证和给排行榜添加分数。这是从主ContentView视图调用的。我不知道如何让它显示排行榜(如果玩家还没有登录,甚至是游戏中心登录屏幕)。
这是我的GameCenterManager类:

class GameCenterManager {
        var gcEnabled = Bool() // Check if the user has Game Center enabled
        var gcDefaultLeaderBoard = String() // Check the default leaderboardID
        var score = 0
        let LEADERBOARD_ID = "grp.colorMatcherLeaderBoard_1" //Leaderboard ID from Itunes Connect

       // MARK: - AUTHENTICATE LOCAL PLAYER
       func authenticateLocalPlayer() {
        let localPlayer: GKLocalPlayer = GKLocalPlayer.local

           localPlayer.authenticateHandler = {(ViewController, error) -> Void in
               if((ViewController) != nil) {
                   print("User is not logged into game center")
               } else if (localPlayer.isAuthenticated) {
                   // 2. Player is already authenticated & logged in, load game center
                   self.gcEnabled = true

                   // Get the default leaderboard ID
                   localPlayer.loadDefaultLeaderboardIdentifier(completionHandler: { (leaderboardIdentifer, error) in
                    if error != nil { print(error ?? "error1")
                       } else { self.gcDefaultLeaderBoard = leaderboardIdentifer! }
                   })
                    print("Adding GameCenter user was a success")
               } else {
                   // 3. Game center is not enabled on the users device
                   self.gcEnabled = false
                   print("Local player could not be authenticated!")
                print(error ?? "error2")
               }
           }
       } //authenticateLocalPlayer()

        func submitScoreToGC(_ score: Int){
            let bestScoreInt = GKScore(leaderboardIdentifier: LEADERBOARD_ID)
            bestScoreInt.value = Int64(score)
            GKScore.report([bestScoreInt]) { (error) in
                if error != nil {
                    print(error!.localizedDescription)
                } else {
                    print("Best Score submitted to your Leaderboard!")
                }
            }
        }//submitScoreToGc()
    }

下面是ContentView结构:

struct ContentView: View {

        //GameCenter
        init() {
            self.gameCenter = GameCenterManager()
            self.gameCenter.authenticateLocalPlayer()
        }

        @State var score = 0
        var gcEnabled = Bool() //Checks if the user had enabled GameCenter
        var gcDefaultLeaderboard = String() //Checks the default leaderboard ID
        let gameCenter: GameCenterManager

        /*End GameCenter Variables */


        var body: some View {

            HStack {
                Text("Hello, world!")
                Button(action: {
                    self.score += 1
                    print("Score increased by 10. It is now \(self.score)")
                    self.gameCenter.submitScoreToGC(self.score)

                }) {
                    Text("Increase Score")

                }
            }
        }
    }

非常感谢任何帮助解决这个问题。

oewdyzsn

oewdyzsn1#

我有一个固定。
我在我的SwiftUI应用程序Sound Matcher中成功地使用了Game Center。代码片段如下。
代码并没有完全遵循SwiftUI的声明性理念,但它运行得很好。我向SceneDelegate和ContentView添加了代码片段,并使用了一个GameKitHelper类,类似于托马斯为他的测试应用创建的类。我的版本基于我在raywenderlich.com上找到的代码。
实际上我第一次尝试使用符合UIViewControllerRepresentable的结构体,遵循与bg2b相同的思路,但它一直抱怨游戏中心视图控制器需要模态呈现。最终我放弃了,并尝试了目前更成功的方法。
适用于SwiftUI 1.0和iOS 13

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    let contentView = ContentView()
        .environmentObject(GameKitHelper.sharedInstance) // publish enabled state

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, 
            options connectionOptions: UIScene.ConnectionOptions) {
    
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)

        window.rootViewController = UIHostingController(rootView: contentView)
        // new code to create listeners for the messages
        // you will be sending later
        PopupControllerMessage.PresentAuthentication
             .addHandlerForNotification(
                 self, 
                 handler: #selector(SceneDelegate
                     .showAuthenticationViewController))
                
        PopupControllerMessage.GameCenter
            .addHandlerForNotification(
                self, 
                handler: #selector(SceneDelegate
                   .showGameCenterViewController))

        // now we are back to the standard template
        // generated when your project was created
        self.window = window
        window.makeKeyAndVisible()
    }
}
// pop's up the leaderboard and achievement screen
@objc func showGameCenterViewController() {
         if let gameCenterViewController =
             GameKitHelper.sharedInstance.gameCenterViewController {
                    self.window?.rootViewController?.present(
                         gameCenterViewController,
                         animated: true,
                         completion: nil)
         }
  
}
// pop's up the authentication screen
@objc func showAuthenticationViewController() {
    if let authenticationViewController =
        GameKitHelper.sharedInstance.authenticationViewController {
              
           self.window?.rootViewController?.present(
                authenticationViewController, animated: true)
                { GameKitHelper.sharedInstance.enabled  = 
                  GameKitHelper.sharedInstance.gameCenterEnabled }
    }
  }
}

// content you want your app to display goes here
struct ContentView: View {
  

@EnvironmentObject var gameCenter : GameKitHelper
@State private var isShowingGameCenter = false { didSet { 
                        PopupControllerMessage
                           .GameCenter
                           .postNotification() }}
     
var body: some View { 
    VStack {
        if self.gameCenter.enabled
             { 
            Button(action:{ self.isShowingGameCenter.toggle()})
                { Text(
                  "Press to show leaderboards and achievements")}
             } 
        // The authentication popup will appear when you first enter
        // the view            
        }.onAppear() {GameKitHelper.sharedInstance
                               .authenticateLocalPlayer()}
    }
}

import GameKit
import UIKit
 
// Messages sent using the Notification Center to trigger 
// Game Center's Popup screen
public enum PopupControllerMessage : String
{
 case PresentAuthentication = "PresentAuthenticationViewController"
 case GameCenter = "GameCenterViewController"
}

extension PopupControllerMessage
{
  public func postNotification() {
     NotificationCenter.default.post(
        name: Notification.Name(rawValue: self.rawValue),
        object: self)
  }
    
  public func addHandlerForNotification(_ observer: Any, 
                                        handler: Selector) {
     NotificationCenter.default .
          addObserver(observer, selector: handler, name:
            NSNotification.Name(rawValue: self.rawValue), object: nil)
  }
    
}

// based on code from raywenderlich.com
// helper class to make interacting with the Game Center easier

open class GameKitHelper: NSObject,  ObservableObject,  GKGameCenterControllerDelegate  {
    public var authenticationViewController: UIViewController?
    public var lastError: Error?

private static let _singleton = GameKitHelper()
public class var sharedInstance: GameKitHelper {
    return GameKitHelper._singleton
}

private override init() {
    super.init()
}
@Published public var enabled :Bool = false
   
public var  gameCenterEnabled : Bool { 
                     return GKLocalPlayer.local.isAuthenticated }

    public func authenticateLocalPlayer () {
        let localPlayer = GKLocalPlayer.local
        localPlayer.authenticateHandler = {(viewController, error) in
           
            self.lastError = error as NSError?
             self.enabled = GKLocalPlayer.local.isAuthenticated
            if viewController != nil {
                self.authenticationViewController = viewController                  
                PopupControllerMessage
                   .PresentAuthentication
                   .postNotification()
            }
        }
    }
   
    public var gameCenterViewController : GKGameCenterViewController? { get {
         
         guard gameCenterEnabled else {  
                  print("Local player is not authenticated")
                  return nil }
        
         let gameCenterViewController = GKGameCenterViewController()
         
         gameCenterViewController.gameCenterDelegate = self
         
         gameCenterViewController.viewState = .achievements
         
         return gameCenterViewController
        }}
    
    open func gameCenterViewControllerDidFinish(_ 
                gameCenterViewController: GKGameCenterViewController) {
   
        gameCenterViewController.dismiss(
                      animated: true, completion: nil)
    }
   
}

更新:对于SwiftUI 2.0和iOS 14,代码更容易

import GameKit

enum Authenticate
{
   static func user() {
       let localPlayer = GKLocalPlayer.local
       localPlayer.authenticateHandler = { _, error in
           guard error == nil else {
               print(error?.localizedDescription ?? "")
               return
           }
           GKAccessPoint.shared.location = .topLeading
           GKAccessPoint.shared.isActive =      
                            localPlayer.isAuthenticated
       }
   }
}

import SwiftUI

// content you want your app to display goes here
struct ContentView: View { 
     
var body: some View { 
      Text( "Start Game") 
        // The authentication popup will appear when you first enter
        // the view            
        }.onAppear() { Authenticate.user()}
    }
}
oo7oh9g9

oo7oh9g92#

在此为您提供部分答案。如果设备(或模拟器)已登录iCloud并且已在设置中启用GameCenter,我可以下载排行榜分数并在SwiftUI列表中显示它们。如果不是这样,我没有尝试显示gameCenter身份验证视图控制器。
感谢您的问题中的代码。我使用了您的GameCenterManager(),但将其放在了我的AppDelegate中:

let gameCenter = GameCenterManager()

下面是我的ShowRankings。swift SwiftUI视图。我能够成功地验证并获得分数。但我仍然有“异常”。我第一次运行这个(在模拟器中)我收到预期的“User is not logged into Game Center”(用户未登录到游戏中心)错误,指示您的GameCenterManager中的ViewController不是零(我甚至从来没有尝试过显示它)。但是我能够成功地获得分数并将它们显示在列表中。

import SwiftUI
import GameKit

struct ShowRankings: View {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let leaderBoard = GKLeaderboard()
    @State var scores: [GKScore] = []
    var body: some View {
        VStack {
            Button(action: {
                self.updateLeader()
            }) {
                Text("Refresh leaderboard")
            }
            List(scores, id: \.self) { score in
                Text("\(score.player.alias) \(score.value)")
            }
        }.onAppear() {
            self.appDelegate.gameCenter.authenticateLocalPlayer()
            self.updateLeader()
        }
    }
    func updateLeader() {
        let leaderBoard: GKLeaderboard = GKLeaderboard()
        leaderBoard.identifier = "YOUR_LEADERBOARD_ID_HERE"
        leaderBoard.timeScope = .allTime
        leaderBoard.loadScores { (scores, error) in
            if let error = error {
                debugPrint("leaderboard loadScores error \(error)")
            } else {
                guard let scores = scores else { return }
                self.scores = scores
            }
        }
    }
}
utugiqy6

utugiqy63#

另一种解决方案是为GameCenter创建一个UIViewControllerRepresentable,它需要一个排行榜ID来打开。这使得打开特定排行榜变得简单。

public struct GameCenterView: UIViewControllerRepresentable {
    let viewController: GKGameCenterViewController
    
    public init(leaderboardID : String?) {
        
        if leaderboardID != nil {
            self.viewController = GKGameCenterViewController(leaderboardID: leaderboardID!, playerScope: GKLeaderboard.PlayerScope.global, timeScope: GKLeaderboard.TimeScope.allTime)
        }
        else{
            self.viewController = GKGameCenterViewController(state: GKGameCenterViewControllerState.leaderboards)
        }
        
    }
    
    public func makeUIViewController(context: Context) -> GKGameCenterViewController {
        let gkVC = viewController
        gkVC.gameCenterDelegate = context.coordinator
        return gkVC
    }
    
    public func updateUIViewController(_ uiViewController: GKGameCenterViewController, context: Context) {
        return
    }
    
    public func makeCoordinator() -> GKCoordinator {
        return GKCoordinator(self)
    }
}

public class GKCoordinator: NSObject, GKGameCenterControllerDelegate {
    var view: GameCenterView
    
    init(_ gkView: GameCenterView) {
        self.view = gkView
    }
    
    public func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
        gameCenterViewController.dismiss(animated: true, completion: nil)
    }
}

要使用,只需在需要显示排行榜的位置添加以下。

GameCenterView(leaderboardID: "leaderBoardID")

相关问题