Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

SkipGameServices

This module provides a compatibility API corresponding to Apple's GameKit framework, using Google Play Games Services.

Currently, SkipGameServices can:

  • Log the user in to Game Center/Play Games
  • Report achievement progress
  • Submit leaderboard scores
  • Save, restore, and delete saved games

Setup

To include this framework in your project, add the following dependency to your Package.swift file:

let package = Package(
    name: "my-package",
    products: [
        .library(name: "MyProduct", targets: ["MyTarget"]),
    ],
    dependencies: [
        .package(url: "https://github.com/skiptools/skip-game-services.git", "0.0.0"..<"2.0.0"),
    ],
    targets: [
        .target(name: "MyTarget", dependencies: [
            .product(name: "SkipGameServices", package: "skip-game-services")
        ])
    ]
)

Table of Contents

Setting up for Game Center / Play Games Services

It can be very tricky to get your app set up properly if you've never done it before. It requires finicky work in App Store Connect, in the Google Play Console, in your Xcode project settings, and in your AndroidManifest.xml.

There is no way to provide sample code that works "out of the box," because you'd have to set things up in the consoles first, and copy and paste ID numbers and settings to exactly the right place.

For your first attempt at using GameKit/PGS, we recommend setting up a "Hello, World" app in a non-Skip native Swift app and a non-Skip native Kotlin app first. Once you kinda sorta know how to use these libraries in isolation, you can use SkipGameServices to write your achievement, leaderboard, and cloud-save code once in Swift and run it on iOS and Android.

Follow the documentation here:

  • Initializing and configuring Game Center
    • Enable the Game Center capability in your Xcode project (this will require a registered development team in App Store Connect with provisioning set up)
    • Create a GameCenterResources.gamekit file defining your achievements and leaderboards
    • Configure your project scheme to "Enable Debug Mode" in the "Run Configuration" section.
    • Launch your app on a physical device. (No simulators allowed!)
    • Use the "Debug > GameKit > Manage Game Progress" menu to access local game progress.
  • Set up Google Play Games Services
    • Sign in to the Google Play Console with a valid developer account
    • Create a Google Cloud Project
    • "Grow users > Play Games Services > Setup and management > Configuration" and select your Google Cloud Project
    • Fill out properties
      • Consider enabling Saved Games
    • Define achievements and leaderboards
    • Generate an OAuth 2.0 client ID
    • Enable testing
    • Add the PGS numeric application ID to your AndroidManifest.xml https://developer.android.com/games/pgs/android/android-signin
    • Test on a physical device or an emulator with the Google Play Store enabled
    • Troubleshooting Play Games Services in Android games

Authentication

The authentication flow for both GameKit and Play Games Services is quite similar. The platform requires you to first check whether the user is authenticated, which you'd normally do at launch, via SkipGameServices.shared.refreshAuthentication().

In GameKit, you use GKLocalPlayer.local.isAuthenticated to detect if the user is authenticated, and you can read the current user's name with GKLocalPlayer.local.displayName.

The SkipGameServices.shared object is a singleton marked @Observable, so you can add it to your SwiftUI/SkipUI app like this, and have your UI automatically update when isAuthenticated changes.

import SwiftUI
import SkipGameServices

struct ContentView: View {
    @Bindable private var gameServices = SkipGameServices.shared
    var body: some View {
        VStack {
            Text("Authenticated: \(gameServices.isAuthenticated ? "Yes" : "No")")
            if gameServices.isAuthenticated {
                Text("Hello, \(GKLocalPlayer.local.displayName)")
            } else {
                Button("Sign in") {
                    Task {
                        try? await gameServices.authenticate()
                    }
                }
            }
        }
        .task {
            try? await gameServices.refreshAuthentication()
        }
    }
}

When you first refresh authentication, GameKit/PGS may show a full-screen sign-in prompt. If the user dismisses the prompt, GameKit/PGS won't show it again. You can call SkipGameServices.shared.authenticate() to sign in after the user dismisses the prompt.

(GameKit doesn't actually offer an API to request sign in after dismissing the prompt. On iOS, authenticate() opens Game Center in the iOS Settings app.)

Achievements

Important

Requires special configuration on Android

Registering Android Achievement IDs

Above and beyond just defining your achievements in the Google Play Console, there's a crucial difference between achievements on Google Play Games Services and achievements on App Store Connect.

App Store Connect lets you specify a logical "Achievement ID", e.g. dragonslayer, which becomes the identifier property of the GKAchievement object. In addition, you can specify a non-translated "Reference Name" (used only internally) and set the display name in any number of localizations.

Play Games Services randomly generates an ID number for every achievement, like this: CgkI7_2_yPQFEAIQAQ. If you want to use a logical identifier for your achievement, Google recommends adding a strings.xml file mapping arbitrary names to Google's randomized achievement IDs.

SkipGameServices provides a custom static extension method, GKAchievement.registerAchievementIdentifiers(:), which you can use to register your Google Play Services opaque IDs by their logical IDs, matching iOS.

try GKAchievement.registerAchievementIdentifiers([
    "dragonslayer": "CgkI7_2_yPQFEAIQAQ",
    "flawless": "CgkIx4Hzt8oGEAIQGQ",
    "tycoon": "CgkIx4Hzt8oGEAIQCw",
])

Reporting Achievement Progress

Use GKAchievement.report(:) to report achievement progress.

try GKAchievement.registerAchievementIdentifiers([
    "dragonslayer": "CgkI7_2_yPQFEAIQAQ",
])
let achievement = GKAchievement(identifier: "dragonslayer")
achievement.percentComplete = 100.0
try await GKAchievement.report([achievement])

Loading and Displaying Achievements

Use GKAchievement.loadAchievements() to load achievements, like this:

import SwiftUI
import SkipGameServices

struct ContentView: View {
    @Bindable private var gameServices = SkipGameServices.shared
    @State private var isLoading = true
    @State private var achievements: [GKAchievement] = []
    @State private var achievementDescriptions: [String: GKAchievementDescription] = [:]

    var body: some View {
        ScrollView(.vertical) {
            VStack {
                if isLoading {
                    ProgressView()
                } else if achievements.isEmpty {
                    Text("No achievements loaded")
                } else {
                    ForEach(achievements, id: \.identifier) { achievement in
                        Text(achievementDescriptions[achievement.identifier]?.title ?? achievement.identifier)
                    }
                }
            }
        }
        .task {
            try? await gameServices.refreshAuthentication()
        }
        .task(id: gameServices.isAuthenticated) {
            guard gameServices.isAuthenticated else {
                isLoading = false
                achievements = []
                achievementDescriptions = [:]
                return
            }
            isLoading = true
            defer { isLoading = false }
            do {
                try GKAchievement.registerAchievementIdentifiers([
                    "dragonslayer": "CgkI7_2_yPQFEAIQAQ",
                ])
                achievements = try await GKAchievement.loadAchievements()
                for description in try await GKAchievementDescription.loadAchievementDescriptions() {
                    achievementDescriptions[description.identifier] = description
                }
            } catch {
                achievements = []
            }
        }
    }
}

Leaderboards

Important

Requires special configuration on Android

Like achievements, leaderboard identifiers differ between App Store Connect and Play Games Services.

On iOS, you use your logical leaderboard ID (for example, highscore) when calling GKLeaderboard APIs. On Android, Play Games uses randomized opaque IDs like CgkI7_2_yPQFEAIQAg.

To use the same logical IDs on both platforms, register a mapping before loading leaderboards or submitting leaderboard scores:

try GKLeaderboard.registerLeaderboardIdentifiers([
    "highscore": "CgkI7_2_yPQFEAIQAg",
])

let leaderboards = try await GKLeaderboard.loadLeaderboards(IDs: ["highscore"])
if let leaderboard = leaderboards.first {
    try await leaderboard.submitScore(12_345, context: 0, player: GKLocalPlayer.local)
}

Displaying Achievements and Leaderboards

// The GKAccessPoint.trigger() function accepts a non-optional `handler:` callback
// (You probably just want to leave it blank)
GKAccessPoint.shared.trigger(.achievements) {}
GKAccessPoint.shared.trigger(.leaderboards) {}

// This API requires you to call GKLeaderboard.registerLeaderboardIdentifiers() first
GKAccessPoint.shared.trigger(
    leaderboardID: "highscore",
    playerScope: .global, // or .friendsOnly
    timeScope: .allTime // or .today, or .week
) {}

Saved Games

Load saved games with GKLocalPlayer.local.fetchSavedGames(). (Note that the resulting saved games may be conflicted; you'll need to detect and resolve the conflicts; see below.)

import SwiftUI
import SkipGameServices

struct ContentView: View {
    @Bindable private var gameServices = SkipGameServices.shared
    @State private var isLoading = true
    @State private var savedGames: [GKSavedGame] = []

    var body: some View {
        VStack {
            if isLoading {
                ProgressView()
            } else if savedGames.isEmpty {
                Text("No saved games loaded")
            } else {
                List(savedGames, id: \.name) { savedGame in
                    Text(savedGame.name ?? "")
                }
            }
        }
        .task {
            try? await gameServices.refreshAuthentication()
        }
        .task(id: gameServices.isAuthenticated) {
            guard gameServices.isAuthenticated else {
                isLoading = false
                savedGames = []
                return
            }
            isLoading = true
            defer { isLoading = false }
            savedGames = (try? await GKLocalPlayer.local.fetchSavedGames()) ?? []
            // don't forget to resolve conflicts! see below
        }
    }
}

Save a game by name with GKLocalPlayer.local.saveGameData(_:withName:).

let data = Data("example".utf8)
try await GKLocalPlayer.local.saveGameData(data, withName: "test")

Detecting and resolving conflicts in saved games

GameKit documentation tells you to implement GKSavedGameListener and register with GKLocalPlayer.register(_:) to be notified of conflicts with player(_:hasConflictingSavedGames:).

That mostly works in GameKit apps, because GameKit automatically synchronizes saved games in the background. Play Games Services doesn't do that, and so SkipGameServices will never call your GKSavedGameListener in the background.

(GKSavedGameListener only "mostly works," because GameKit will frequently call your GKSavedGameListener handler multiple times for the same conflict. didModifySavedGame is even harder to work with, as it can call you back multiple times about the modifications you just made, including conflicts that you just resolved.)

Instead, you must detect and resolve save conflicts by merging the conflicted entries returned from fetchSavedGames(). (This is a best practice in GameKit as well, because there's no guarantee that your listener will resolve all conflicts before fetchSavedGames() is called.)

It requires a lot of code to do that, so we've provided a convenience extension, GKLocalPlayer.local.fetchSavedGamesResolvingConflicts().

let resolved = try await GKLocalPlayer.local.fetchSavedGamesResolvingConflicts()

By default, it prefers the most recently modified save, but you can pass in your own GKSavedGame.ConflictResolver (another extension of ours), like this:

let resolved = try await GKLocalPlayer.local.fetchSavedGamesResolvingConflicts() { name, first, rest in
    // arbitrarily pick the first save’s payload
    return try await first.loadData()
}

If you need your app to synchronize the latest saved games, design your app to poll fetchSavedGamesResolvingConflicts(). If you do that, on iOS, you won't need GKSavedGameListener. (We recommend avoiding using GKSavedGameListener for anything besides logging.)

But, if you really want to implement GKSavedGameListener on iOS, you can use a GKSavedGame.ConflictResolver there, too. You can use our GKSavedGame.detectAndResolveConflicts(in:with:) function to resolve conflicts. Here's an example using our GKSavedGame.mostRecentConflictResolver.

// In this example, you'll use our resolver, but you could implement your own
let resolver: GKSavedGame.ConflictResolver = GKSavedGame.mostRecentConflictResolver
class SavedGameListener: NSObject, GKSavedGameListener {
    func player(_ player: GKPlayer, hasConflictingSavedGames savedGames: [GKSavedGame]) {
        Task {
            try? await GKSavedGame.detectAndResolveConflicts(in: savedGames, with: resolver)
        }
    }
}
GKLocalPlayer.local.register(SavedGameListener())
// ...
try await GKLocalPlayer.local.fetchSavedGamesResolvingConflicts(with: resolver)

Building

This project is a Swift Package Manager module that uses the Skip plugin to build the package for both iOS and Android.

Testing

The module can be tested using the standard swift test command or by running the test target for the macOS destination in Xcode, which will run the Swift tests as well as the transpiled Kotlin JUnit tests in the Robolectric Android simulation environment.

Parity testing can be performed with skip test, which will output a table of the test results for both platforms.

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages