Swift Client Guide #

This client library guide will show you how to use the core Nakama features in Swift by showing you how to develop the Nakama specific parts (without full game logic or UI) of an Among Us (external) inspired game called Sagi-shi (Japanese for “Imposter”).

Sagi-shi gameplay screen
Sagi-shi gameplay

Prerequisites #

Before proceeding ensure that you have:

Full API documentation #

For the full API documentation please visit the API docs.

Installation #

The client is available on Heroic Labs GitHub Releases, as a Swift Package.

Swift Package Manager #

Add the following to your Package.swift:

1
2
3
4
5
6
let package = Package(
	// ...
	dependencies: [
    .package(url: "https://github.com/heroiclabs/nakama-swift.git", .upToNextMajor(from: "1.0.0"))
]
)

Or paste the git url in your Xcode project using Package Dependencies settings

Updates #

New versions of the Nakama Swift Client and the corresponding improvements are documented in the Release Notes.

Asynchronous programming #

Many methods of Nakama’s APIs available in the Swift SDK are asynchronous and non-blocking.

Sagi-shi calls async methods using the await operator to not block the calling thread so that the game is responsive and efficient.

1
await client.authenticateDevice("<deviceId>");

Read about async functions.

Handling exceptions #

Network programming requires additional safeguarding against connection and payload issues.

API calls in Sagi-shi are surrounded with a try block and a catch clause to gracefully handle errors:

1
2
3
4
5
do {
    try await client.authenticateDevice("<deviceId>")
} catch let error as NSError {
    print("Error authenticating device: \(error.code):\(error.message)")
}

Read more about error handing in Swift.

Getting started #

Learn how to get started using the Nakama Client and Socket objects to start building Sagi-shi and your own game.

Nakama Client #

The Nakama Client connects to a Nakama Server and is the entry point to access Nakama features. It is recommended to have one client per server per game.

To create a client for Sagi-shi pass in your server connection details:

1
2
3
4
5
let client = GrpcClient(
    serverKey: "defaultkey",
    host: "127.0.0.1",
    ssl: false
)

Configuring the Request Timeout Length #

Each request to Nakama from the client must complete in a certain period of time before it is considered to have timed out. You can configure how long this period is (in seconds) by passing the value for deadlineAfter parameter on the client init. It defaults to 20:

1
let client = GrpcClient(serverKey: "defaultkey", deadlineAfter: 1)

Nakama Socket #

The Nakama Socket is used for gameplay and real-time latency-sensitive features such as chat, parties, matches and RPCs.

From the client create a socket:

1
2
3
let socket = client.createSocket()

socket.connect(session: session, appearOnline: true)

Authentication #

Nakama has many authentication methods and supports creating custom authentication on the server.

Sagi-shi will use device and Facebook authentication, linked to the same user account so that players can play from multiple devices.

Sagi-shi login screen
Login screen and Authentication options

Device authentication #

Nakama Device Authentication uses the physical device’s unique identifier to easily authenticate a user and create an account if one does not exist.

When using only device authentication, you don’t need a login UI as the player can automatically authenticate when the game launches.

Authentication is an example of a Nakama feature accessed from a Nakama Client instance. In this example we use UIDevice API available in iOS to get device unique id:

1
2
3
4
5
6
7
8
guard let deviceId = await UIDevice.current.identifierForVendor?.uuidString else { return }

do {
    let session = try await client.authenticateDevice(id: deviceId, create: create, username: "mycustomusername")
    print("Successfully authenticated:", session)
} catch {
    debugPrint(error)
}

Facebook authentication #

Nakama Facebook Authentication is an easy to use authentication method which lets you optionally import the player’s Facebook friends and add them to their Nakama Friends list.

1
2
3
4
5
6
7
8
9
let oauthToken = "<token>"
var importFriends = true

do {
    let session = try await client.authenticateFacebook(accessToken: oauthToken, create: true, username: "mycustomusername", importFriends: importFriends)
    print("Successfully authenticated:", session)
} catch {
    debugPrint(error)
}

Custom authentication #

Nakama supports Custom Authentication methods to integrate with additional identity services.

See the Itch.io custom authentication recipe for an example.

Linking authentication #

Nakama allows players to Link Authentication methods to their account once they have authenticated.

Linking Device ID authentication

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Acquiring the unique device ID has been shortened for brevity, see previous example.
var deviceId = "<uniqueDeviceId>"

// Link Device Authentication to existing player account.
do {
    try await client.linkDevice(session: session, deviceId: deviceId)
    print("Successfully linked Device ID authentication to existing player account")
} catch {
    debugPrint(error)
}

Linking Facebook authentication

1
2
3
4
5
6
7
8
9
var oauthToken = "<token>"
var importFriends = true

do {
    try await client.linkFacebook(session: session, oauthToken: oauthToken, importFriends: importFriends)
    print("Successfully linked Facebook authentication to existing player account")
} catch {
    debugPrint(error)
}

Session variables #

Nakama Session Variables can be stored when authenticating and will be available on the client and server as long as the session is active.

Sagi-shi uses session variables to implement analytics, referral and rewards programs and more.

Store session variables by passing them as an argument when authenticating:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let vars = [
    "deviceId": deviceId,
    "deviceOs": deviceOs,
    "inviteUserId": "<someUserId>",
    // ...
]

do {
    let session = try await client.authenticateDevice(deviceId: deviceId, create: true, username: "mycustomusername", vars: vars)
    print("Successfully authenticated:", session)
} catch {
    debugPrint(error)
}```

To access session variables on the Client use the `vars` property on the `session` object:

```swift
let deviceOs = session.vars["deviceOs"]

Session lifecycle #

Nakama Sessions expire after a time set in your server configuration. Expiring inactive sessions is a good security practice.

Nakama provides ways to restore sessions, for example when Sagi-shi players re-launch the game, or refresh tokens to keep the session active while the game is being played.

Use the auth and refresh tokens on the session object to restore or refresh sessions.

Store the tokens for use later:

1
2
var authToken = session.token
var refreshToken = session.refresh_token

Restore a session without having to re-authenticate:

1
session = try await client.restoreSession(authToken: authToken, refreshToken: refreshToken)

Check if a session has expired or is close to expiring and refresh it to keep it alive:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
if session.hasExpired(offset: Date().addingTimeInterval(5 * 60)) { // Session about to expire in 5 minutes
    do {
        session = try await client.refreshSession(session: session)
    } catch {
        // Couldn't refresh the session so reauthenticate
        session = try await client.authenticateDevice(deviceId: deviceId)
        var refreshToken = session.refresh_token
    }

    var authToken = session.token
}

Automatic session refresh #

The Swift client library includes a feature where sessions close to expiration are automatically refreshed.

This is enabled by default but can be configured when first creating the Nakama client using the following parameters:

  • autoRefreshSession - Boolean value indicating if this feature is enabled, true by default
  • expiredTimespanMs - The time prior to session expiry when auto-refresh will occur, set to 300000 (5 minutes) be default

Ending sessions #

Logout and end the current session:

1
try await client.sessionLogout(session: session)

User accounts #

Nakama User Accounts store user information defined by Nakama and custom developer metadata.

Sagi-shi allows players to edit their accounts and stores metadata for things like game progression and in-game items.

Sagi-shi player profile screen
Player profile

Get the user account #

Many of Nakama’s features are accessible with an authenticated session, like fetching a user account.

Get a Sagi-shi player’s full user account with their basic user information and user id:

1
2
3
4
5
var account = try await client.getAccount(session: session)
var user = account.user
var username = account.user.username
var avatarUrl = account.user.avatarUrl
var userId = account.user.id

Update the user account #

Nakama provides easy methods to update server stored resources like user accounts.

Sagi-shi players need to be able to update their public profiles:

1
2
3
4
5
6
7
var newUsername = "NotTheImp0ster"
var newDisplayName = "Innocent Dave"
var newAvatarUrl = "https://example.com/imposter.png"
var newLangTag = "en"
var newLocation = "Edinburgh"
var newTimezone = "BST"
try await client.updateAccount(session: session, username: newUsername, displayName: newDisplayName, avatarURL: newAvatarUrl, langTag: newLangTag, location: newLocation, timezone: newTimezone)

Getting users #

In addition to getting the current authenticated player’s user account, Nakama has a convenient way to get a list of other players’ public profiles from their ids or usernames.

Sagi-shi uses this method to display player profiles when engaging with other Nakama features:

1
var users = try await client.getUsers(session: session, ids: ["<AnotherUserId>"])

Storing metadata #

Nakama User Metadata allows developers to extend user accounts with public user fields.

User metadata can only be updated on the server. See the updating user metadata recipe for an example.

Sagi-shi will use metadata to store what in-game items players have equipped:

Reading metadata #

Get the updated account object and parse the JSON metadata:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Get the updated account object.
var account = try await client.getAccount(session: session)

// Parse the account user metadata.
var metadata = account.user.metadata
print
(
    "Title: \(metadata["title"])\n" +
    "Hat: \(metadata["hat"])\n" +
    "Skin: \(metadata["skin"])\n"
)

Wallets #

Nakama User Wallets can store multiple digital currencies as key/value pairs of strings/integers.

Players in Sagi-shi can unlock or purchase titles, skins and hats with a virtual in-game currency.

Accessing wallets #

Parse the JSON wallet data from the user account:

1
2
3
4
5
6
7
var account = try await client.getAccount(session: session)
var wallet = account.wallet
var keys = wallet.keys

keys.forEach { currency in
    print("\(currency): \(wallet[currency])")
}

Updating wallets #

Wallets can only be updated on the server. See the user account virtual wallet documentation for an example.

Validating in-app purchases #

Sagi-shi players can purchase the virtual in-game currency through in-app purchases that are authorized and validated to be legitimate on the server.

See the In-app Purchase Validation documentation for examples.

Storage Engine #

The Nakama Storage Engine is a distributed and scalable document-based storage solution for your game.

The Storage Engine gives you more control over how data can be accessed and structured in collections.

Collections are named, and store JSON data under a unique key and the user id.

By default, the player has full permission to create, read, update and delete their own storage objects.

Sagi-shi players can unlock or purchase many items, which are stored in the Storage Engine.

Sagi-shi player items screen
Player items

Reading storage objects #

Create a new storage object id with the collection name, key and user id. Then read the storage objects and parse the JSON data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var readObjectId = StorageObjectId(collection: "Unlocks", key: "Hats", userId: session.user.id)

do {
    let result = try await client.readStorageObjects(session: session, objectIds: [readObjectId])
    if let storageObject = result.objects.first {
        let unlockedHats = try JSONSerialization.jsonObject(with: storageObject.value.data(using: .utf8)!, options: []) as! [String: [String]]
        print("Unlocked hats: \(unlockedHats["Hats"]!)")
    }
} catch {
    debugPrint(error)
}

To read other players’ public storage objects use their UserId instead. Remember that players can only read storage objects they own or that are public (PermissionRead value of 2).

Writing storage objects #

Nakama allows developers to write to the Storage Engine from the client and server.

Consider what adverse effects a malicious user can have on your game and economy when deciding where to put your write logic, for example data that should only be written authoritatively (i.e. game unlocks or progress).

Sagi-shi allows players to favorite items for easier access in the UI and it is safe to write this data from the client.

Create a write storage object with the collection name, key and JSON encoded data. Finally, write the storage objects to the Storage Engine:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var favoriteHats = [
    "hats": ["cowboy", "alien"]
]

var writeObject = WriteStorageObject(collection: "favorites", key: "Hats", value: favoriteHats, permissionRead: 1, permissionWrite: 1)

do {
    try await client.writeStorageObjects(session: session, objects: [writeObject])
} catch {
    debugPrint(error)
}

You can also pass multiple objects to the WriteStorageObjects method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var writeObjects = [
    WriteStorageObject(collection: "favorites", key: "Hats", value: favoriteHats, permissionRead: 1, permissionWrite: 1),
    WriteStorageObject(collection: "favorites", key: "Skins", value: favoriteSkins, permissionRead: 1, permissionWrite: 1)
]

do {
    try await client.writeStorageObjects(session: session, objects: writeObjects)
} catch {
    debugPrint(error)
}

Conditional writes #

Storage Engine Conditional Writes ensure that write operations only happen if the object hasn’t changed since you accessed it.

This gives you protection from overwriting data, for example the Sagi-shi server could have updated an object since the player last accessed it.

To perform a conditional write, add a version to the write storage object with the most recent object version:

1
2
3
4
5
6
7
8
// Assuming we already have a storage object (storageObject)
var writeObject = WriteStorageObject(collection: storageObject.collection, key: storageObject.key, value: "<NewJSONValue>", permissionRead: 1, permissionWrite: 0, version: storageObject.version)

do {
    try await client.writeStorageObjects(session: session, objects: [writeObject])
} catch {
    debugPrint(error)
}

Listing storage objects #

Instead of doing multiple read requests with separate keys you can list all the storage objects the player has access to in a collection.

Sagi-shi lists all the player’s unlocked or purchased titles, hats and skins:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var limit = 3
var cursor: String? = nil
var unlocksObjectList = try await client.listStorageObjects(session: session, collection: "Unlocks", limit: limit, cursor: cursor)

unlocksObjectList.objects.forEach { unlockStorageObject in
    switch unlockStorageObject.key {
    case "Titles":
        let unlockedTitles = try JSONSerialization.jsonObject(with: unlockStorageObject.value.data(using: .utf8)!, options: []) as! [String: [String]]
        // Display the unlocked titles
    case "Hats":
        let unlockedHats = try JSONSerialization.jsonObject(with: unlockStorageObject.value.data(using: .utf8)!, options: []) as! [String: [String]]
        // Display the unlocked hats
    case "Skins":
        let unlockedSkins = try JSONSerialization.jsonObject(with: unlockStorageObject.value.data(using: .utf8)!, options: []) as! [String: [String]]
        // Display the unlocked skins
    default:
        break
    }
}

Paginating results #

Nakama methods that list results return a cursor which can be passed to subsequent calls to Nakama to indicate where to start retrieving objects from in the collection.

For example:

  • If the cursor has a value of 5, you will get results from the fifth object.
  • If the cursor is nil, you will get results from the first object.
1
var objectList = try await client.listStorageObjects(session: session, collection: "<CollectionName>", limit: limit, cursor: objectList.cursor)

Protecting storage operations on the server #

Nakama Storage Engine operations can be protected on the server to protect data the player shouldn’t be able to modify (i.e. game unlocks or progress). See the writing to the Storage Engine authoritatively recipe.

Remote Procedure Calls #

The Nakama Server allows developers to write custom logic and expose it to the client as RPCs.

Sagi-shi contains various logic that needs to be protected on the server, like checking if the player owns equipment before equipping it.

Creating server logic #

See the handling player equipment authoritatively recipe for an example of creating a remote procedure to check if the player owns equipment before equipping it.

Client RPCs #

Nakama Remote Procedures can be called from the client and take optional JSON payloads.

The Sagi-shi client makes an RPC to securely equip a hat:

1
2
3
4
5
6
7
var payload = ["item": "cowboy"]
do {
    let response = try await client.rpc(session: session, id: "EquipHat", payload: payload)
    print("New hat equipped successfully", response)
} catch {
    debugPrint(error)
}

Socket RPCs #

Nakama Remote Procedures can also be called from the socket when you need to interface with Nakama’s real-time functionality. These real-time features require a live socket (and corresponding session identifier). RPCs can be made on the socket carrying this same identifier.

1
var response = try await socket.rpc(id: "<rpcId>", payload: "<payloadString>")

Friends #

Nakama Friends offers a complete social graph system to manage friendships amongst players.

Sagi-shi allows players to add friends, manage their relationships and play together.

Sagi-shi Friends screen
Friends screen

Adding friends #

Adding a friend in Nakama does not immediately add a mutual friend relationship. An outgoing friend request is created to each user, which they will need to accept.

Sagi-shi allows players to add friends by their usernames or user ids:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Add friends by Username.
var usernames = ["AlwaysTheImposter21", "SneakyBoi"]
do {
    try await client.addFriends(session: session, usernames: usernames)
} catch {
    debugPrint(error)
}

// Add friends by User ID.
var ids = ["<SomeUserId>", "<AnotherUserId>"]
do {
    try await client.addFriends(session: session, ids: ids)
} catch {
    debugPrint(error)
}

Friendship states #

Nakama friendships are categorized with the following states:

ValueState
0Mutual friends
1An outgoing friend request pending acceptance
2An incoming friend request pending acceptance
3Blocked by the user

Listing friends #

Nakama allows developers to list the player’s friends based on their friendship state.

Sagi-shi lists the 20 most recent mutual friends:

1
2
3
4
5
6
7
let limit = 1000 // Limit is capped at 1000
let friendshipState = 0
var result = try await client.listFriends(session: session, limit: limit)

result.friends.forEach { friend in
    print("ID: \(friend.user.id)")
}

Accepting friend requests #

When accepting a friend request in Nakama the player adds a bi-directional friend relationship.

Nakama takes care of changing the state from pending to mutual for both.

In a complete game you would allow players to accept individual requests.

Sagi-shi just fetches and accepts all the incoming friend requests:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var limit = 1000
var result = try await client.listFriends(session: session, limit: limit)

result.friends.forEach { friend in
    do {
        try await client.addFriends(session: session, ids: [friend.user.id])
    } catch {
        debugPrint(error)
    }
}

Deleting friends #

Sagi-shi players can remove friends by their username or user id:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Delete friends by User ID.
var ids = ["<SomeUserId>", "<AnotherUserId>"]
do {
    try await client.deleteFriends(session: session, ids: ids)
} catch {
    debugPrint(error)
}

// Delete friends by Username.
var usernames = ["AlwaysTheImposter21", "SneakyBoi"]
do {
    try await client.deleteFriends(session: session, ids: [], usernames: usernames)
} catch {
    debugPrint(error)
}

Blocking users #

Sagi-shi players can block others by their username or user id:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Block friends by User ID.
var ids = ["<SomeUserId>", "<AnotherUserId>"]
do {
    try await client.blockFriends(session: session, ids: ids)
} catch {
    debugPrint(error)
}

// Block friends by Username.
var usernames = ["AlwaysTheImposter21", "SneakyBoi"]
do {
    try await client.blockFriends(session: session, usernames: usernames)
} catch {
    debugPrint(error)
}

Learn more about blocking friends and the associated relationship states.

Blocked users can listed just like listing friends but using the corresponding friendship state (3).

Status & Presence #

Nakama Status & Presence has a real-time status and presence service that allows users to set their online presence, update their status message and follow other user’s updates.

Players don’t have to be friends with others they want to follow.

Sagi-shi uses status messages and online presences to notify players when their friends are online and share matches.

Sagi-shi status update screen
Updating player status

Follow users #

The Nakama real-time APIs allow developers to subscribe to events on the socket, like a status presence change, and receive them in real-time.

The method to follow users also returns the current online users, known as presences, and their status.

Sagi-shi follows a player’s friends and notifies them when they are online:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Subscribe to the Status event.
socket.onStatusPresence = { presenceEvent in
    presenceEvent.joins.forEach { presence in
        print("\(presence.username) is online with status: \(presence.status)")
    }
    presenceEvent.leaves.forEach { presence in
        print("\(presence.username) went offline")
    }
}

// Follow mutual friends and get the initial Status of any that are currently online.
var friendsResult = try await client.listFriends(session: session, state: 0, limit: 1000, cursor: nil)
var friendIds = friendsResult.friends.map { friend in
    return friend.user.id
}
var result = try await socket.followUsers(userIds: friendIds)

result.presences.forEach { presence in
    print("\(presence.username) is online with status: \(presence.status)")
}

Unfollow users #

Sagi-shi players can unfollow others:

1
try await socket.unfollowUsers(userIds: ["<UserId>"])

Updating player status #

Sagi-shi players can change and publish their status to their followers:

1
try await socket.updateStatus(status: "Viewing the Main Menu")

Groups #

Nakama Groups is a group or clan system with public/private visibility, user memberships and permissions, metadata and group chat.

Sagi-shi allows players to form and join groups to socialize and compete.

Sagi-shi groups screen
Groups list screen

Creating groups #

Groups have a public or private “open” visibility. Anyone can join public groups, but they must request to join and be accepted by a superadmin/admin of a private group.

Sagi-shi players can create groups around common interests:

1
2
3
4
5
6
7
8
9
var groupName = "Imposters R Us"
var description = "A group for people who love playing the imposter."

do {
    let group = try await client.createGroup(session: session, name: groupName, description: description, avatarUrl: nil, langTag: nil, open: true, maxCount: 100)
    print("Group created successfully", group)
} catch {
    debugPrint(error)
}

Update group visibility #

Nakama allows group superadmin or admin members to update some properties from the client, like the open visibility:

1
2
3
4
5
6
7
8
var groupId = "<groupId>"

do {
    try await client.updateGroup(session: session, groupId: groupId, name: nil, description: nil, avatarUrl: nil, langTag: nil, open: false, maxCount: nil)
    print("Group updated successfully")
} catch {
    debugPrint(error)
}

Update group size #

Other properties, like the group’s maximum member size, can only be changed on the server.

See the updating group size recipe for an example, and the Groups server function reference to learn more about updating groups on the server.

Sagi-shi group edit screen
Sagi-shi group edit

Listing and filtering groups #

Groups can be listed like other Nakama resources and also filtered with a wildcard group name.

Sagi-shi players use group listing and filtering to search for existing groups to join:

1
2
3
4
5
6
7
8
9
var limit = 20
var result = try await client.listGroups(session: session, name: "imposter%", limit: limit, cursor: nil)

result.groups.forEach { group in
    print("\(group.name) group is \(group.open)")
}

// Get the next page of results.
var nextResults = try await client.listGroups(session: session, name: "imposter%", limit: limit, cursor: result.cursor)

Deleting groups #

Nakama allows group superadmins to delete groups.

Developers can disable this feature entirely, see the Guarding APIs guide for an example on how to protect various Nakama APIs.

Sagi-shi players can delete groups which they are superadmins for:

1
2
3
4
5
6
7
var groupId = "<groupId>"
do {
    try await client.deleteGroup(session: session, groupId: groupId)
    print("Group deleted successfully")
} catch {
    debugPrint(error)
}

Group metadata #

Like Users Accounts, Groups can have public metadata.

Sagi-shi uses group metadata to store the group’s interests, active player times and languages spoken.

Group metadata can only be updated on the server. See the updating group metadata recipe for an example.

The Sagi-shi client makes an RPC with the group metadata payload:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var payload = [
    "groupId": "<GroupId>",
    "interests": ["Deception", "Sabotage", "Cute Furry Bunnies"],
    "activeTimes": ["9am-2pm Weekdays", "9am-10pm Weekends"],
    "languages": ["English", "German"]
]

do {
    let response = try await client.rpc(session: session, id: "UpdateGroupMetadata", payload: payload)
    print("Successfully updated group metadata", response)
} catch {
    debugPrint(error)
}

Group membership states #

Nakama group memberships are categorized with the following states:

CodePurpose
0SuperadminThere must at least be 1 superadmin in any group. The superadmin has all the privileges of the admin and can additionally delete the group and promote admin members.
1AdminThere can be one of more admins. Admins can update groups as well as accept, kick, promote, demote, ban or add members.
2MemberRegular group member. They cannot accept join requests from new users.
3Join requestA new join request from a new user. This does not count towards the maximum group member count.

Joining a group #

If a player joins a public group they immediately become a member, but if they try and join a private group they must be accepted by a group admin.

Sagi-shi players can join a group:

1
2
3
4
5
6
7
var groupId = "<groupId>"
do {
    try await client.joinGroup(session: session, groupId: groupId)
    print("Group joined successfully")
} catch {
    debugPrint(error)
}

Listing the user’s groups #

Sagi-shi players can list groups they are a member of:

1
2
3
4
5
6
var userId = "<userId>"
var result = try await client.listUserGroups(session: session, userId: userId)

result.userGroups.forEach { userGroup in
    print("Group: name \(userGroup.group.name) State: \(userGroup.state)")
}

Listing members #

Sagi-shi players can list a group’s members:

1
2
3
4
5
6
var groupId = "<groupId>"
var result = try await client.listGroupUsers(session: session, groupId: groupId)

result.groupUsers.forEach { groupUser in
    print("User: ID \(groupUser.user.id) State: \(groupUser.state)")
}

Accepting join requests #

Private group admins or superadmins can accept join requests by re-adding the user to the group.

Sagi-shi first lists all the users with a join request state and then loops over and adds them to the group:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var groupId = "<groupId>"
var result = try await client.listGroupUsers(session: session, groupId: groupId)

result.groupUsers.forEach { groupUser in
    do {
        try await client.addGroupUsers(session: session, groupId: groupId, userIds: [groupUser.user.id])
    } catch {
        debugPrint(error)
    }
}

Promoting members #

Nakama group members can be promoted to admin or superadmin roles to help manage a growing group or take over if members leave.

Admins can promote other members to admins, and superadmins can promote other members up to superadmins.

The members will be promoted up one level. For example:

  • Promoting a member will make them an admin
  • Promoting an admin will make them a superadmin
1
2
3
4
5
6
7
8
var groupId = "<groupId>"
var userId = "<userId>"
do {
    try await client.promoteGroupUsers(session: session, groupId: groupId, userIds: [userId])
    print("User promoted successfully")
} catch {
    debugPrint(error)
}

Demoting members #

Sagi-shi group admins and superadmins can demote members:

1
2
3
4
5
6
7
8
var groupId = "<groupId>"
var userId = "<userId>"
do {
    try await client.demoteGroupUsers(session: session, groupId: groupId, userIds: [userId])
    print("User demoted successfully")
} catch {
    debugPrint(error)
}

Kicking members #

Sagi-shi group admins and superadmins can remove group members:

1
2
3
4
5
6
7
8
var groupId = "<groupId>"
var userId = "<userId>"
do {
    try await client.kickGroupUsers(session: session, groupId: groupId, userIds: [userId])
    print("User kicked successfully")
} catch {
    debugPrint(error)
}

Banning members #

Sagi-shi group admins and superadmins can ban a user when demoting or kicking is not severe enough:

1
2
3
4
5
6
7
8
var groupId = "<groupId>"
var userId = "<userId>"
do {
    try await client.banGroupUsers(session: session, groupId: groupId, userIds: [userId])
    print("User banned successfully")
} catch {
    debugPrint(error)
}

Leaving groups #

Sagi-shi players can leave a group:

1
2
3
4
5
6
7
var groupId = "<groupId>"
do {
    try await client.leaveGroup(session: session, groupId: groupId)
    print("Group left successfully")
} catch {
    debugPrint(error)
}

Chat #

Nakama Chat is a real-time chat system for groups, private/direct messages and dynamic chat rooms.

Sagi-shi uses dynamic chat during matches, for players to mislead each other and discuss who the imposters are, group chat and private/direct messages.

Sagi-shi chat screen
Sagi-shi Chat

Joining dynamic rooms #

Sagi-shi matches have a non-persistent chat room for players to communicate in:

1
2
3
4
5
6
7
var roomName = "<match id>"
var persistence = false
var hidden = false
// 1 = Room, 2 = Direct Message, 3 = Group
var channel = try await socket.joinChat(roomName: roomName, type: 1, persistence: persistence, hidden: hidden)

print("Connected to dynamic room channel: \(channel.id)")

Joining group chat #

Sagi-shi group members can have conversations that span play sessions in a persistent group chat channel:

1
2
3
4
5
6
7
var groupId = "<groupId>"
var persistence = true
var hidden = false
// 1 = Room, 2 = Direct Message, 3 = Group
var channel = try await socket.joinChat(groupId: groupId, type: 3, persistence: persistence, hidden: hidden)

print("Connected to group channel: \(channel.id)")

Joining direct chat #

Sagi-shi players can also chat privately one-to-one during or after matches and view past messages:

1
2
3
4
5
6
7
var userId = "<userId>"
var persistence = true
var hidden = false
// 1 = Room, 2 = Direct Message, 3 = Group
var channel = try await socket.joinChat(userId: userId, type: 2, persistence: persistence, hidden: hidden)

print("Connected to direct message channel: \(channel.id)")

Sending messages #

Sending messages is the same for every type of chat channel. Messages contain chat text and emotes and are sent as JSON serialized data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var channelId = "<channel id>"
var data = ["message": "I think Red is the imposter!"]
do {
    let messageAck = try await socket.writeChatMessage(channelId: channelId, data: data)
    print("Message sent successfully", messageAck)
} catch {
    debugPrint(error)
}

var emoteData = ["emote": "point", "emoteTarget": "<redPlayerUserId>"]
do {
    let messageAck = try await socket.writeChatMessage(channelId: channelId, data: emoteData)
    print("Emote sent successfully", messageAck)
} catch {
    debugPrint(error)
}

Listing message history #

Message listing takes a parameter which indicates if messages are received from oldest to newest (forward) or newest to oldest.

Sagi-shi players can list a group’s message history:

1
2
3
4
5
6
7
8
9
var groupId = "<groupId>"
var limit = 100
var forward = true

var result = try await client.listChannelMessages(session: session, channelId: groupId, limit: limit, forward: forward, cursor: nil)

result.messages.forEach { message in
    print("\(message.username): \(message.content)")
}

Chat also has cacheable cursors to fetch the most recent messages. Read more about cacheable cursors in the listing notifications documentation.

1
2
var cursor = result.cacheableCursor
var nextResults = try await client.listChannelMessages(session: session, channelId: groupId, limit: limit, forward: forward, cursor: cursor)

Updating messages #

Nakama also supports updating messages. It is up to you whether you want to use this feature, but in a game of deception like Sagi-shi it can add an extra element of deception.

For example a player sends the following message:

1
2
3
4
5
6
7
8
var channelId = "<ChannelId>"
var data = ["message": "I think Red is the imposter!"]
do {
    let messageAck = try await socket.writeChatMessage(channelId: channelId, data: data)
    print("Message sent successfully", messageAck)
} catch {
    debugPrint(error)
}

They then quickly edit their message to confuse others:

1
2
3
4
5
6
7
8
var data = ["message": "I think BLUE is the imposter!"]

do {
    let messageAck = try await socket.updateChatMessage(channelId: channelId, messageId: messageSendAck.message.id, data: data)
    print("Message updated successfully", messageAck)
} catch {
    debugPrint(error)
}

Matches #

Nakama supports Server Authoritative and Server Relayed multiplayer matches.

In server authoritative matches the server controls the gameplay loop and must keep all clients up to date with the current state of the game.

In server relayed matches the client is in control, with the server only relaying information to the other connected clients.

In a competitive game such as Sagi-shi, server authoritative matches would likely be used to prevent clients from interacting with your game in unauthorized ways.

For the simplicity of this guide, the server relayed model is used.

Creating matches #

Sagi-shi players can create their own matches and invite their online friends to join:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
var match = try await socket.createMatch()
var friendsList = try await client.listFriends(session: session)
var onlineFriends = friendsList.friends.filter { friend in
    return friend.user.online
}

onlineFriends.forEach { friend in
    var messageData = ["message": "Hey \(friend.username), join me for a match!"]
    var matchId = match.id
    do {
        let channel = try await socket.joinChat(userId: friend.user.id, type: 2, persistence: true, hidden: false)
        let messageAck = try await socket.writeChatMessage(channelId: channel.id, data: messageData)
        print("Message sent successfully", messageAck)
    } catch {
        debugPrint(error)
    }
}

Creating a match by match name

Sagi-shi players can also create matches with a specific match name, this allows them to invite their friends by telling them the name of the match. It should be noted that when creating a match by name (which is an arbitrary name and not something tied to authoritative match handlers), the match will always be a relayed match rather than an authoritative match.

1
2
var matchName = "NoImpostersAllowed"
var match = try await socket.createMatch(name: matchName)

Joining matches #

Sagi-shi players can try to join existing matches if they know the id:

1
2
3
4
5
6
7
var matchId = "<MatchId>"
do {
    let match = try await socket.joinMatch(matchId: matchId)
    print("Joined match successfully", match)
} catch {
    debugPrint(error)
}

Or set up a real-time matchmaker listener and add themselves to the matchmaker:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
socket.onmatchmakermatched = { matchmakerMatched in
    do {
        let match = try await socket.joinMatch(matchmakerMatched)
        print("Joined match successfully", match)
    } catch {
        debugPrint(error)
    }
}

var minPlayers = 2
var maxPlayers = 10
var query = ""

do {
    let matchmakingTicket = try await socket.addMatchmaker(query: query, minCount: minPlayers, maxCount: maxPlayers)
    print("Matchmaking ticket added successfully", matchmakingTicket)
} catch {
    debugPrint(error)
}

Joining matches from player status

Sagi-shi players can update their status when they join a new match:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var status = [
    "Status": "Playing a match",
    "MatchId": "<MatchId>"
]

do {
    try await socket.updateStatus(status: status)
    print("Status updated successfully")
} catch {
    debugPrint(error)
}

When their followers receive the real-time status event they can try and join the match:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
socket.onstatuspresence = { presenceEvent in
    presenceEvent.joins.forEach { presence in
        let status = presence.status as! [String: String]
        if status["MatchId"] != nil {
            do {
                let match = try await socket.joinMatch(matchId: status["MatchId"]!)
                print("Joined match successfully", match)
            } catch {
                debugPrint(error)
            }
        }
    }
}

Listing matches #

Match Listing takes a number of criteria to filter matches by including player count, a match label and an option to provide a more complex search query.

Sagi-shi matches start in a lobby state. The match exists on the server but the actual gameplay doesn’t start until enough players have joined.

Sagi-shi can then list matches that are waiting for more players:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
let minPlayers = 2
let maxPlayers = 10
let limit = 10
let authoritative = true
let label = ""
let query = ""

do {
    let result = try await client.listMatches(session: session, minCount: minPlayers, maxCount: maxPlayers, limit: limit, authoritative: authoritative, label: label, query: query)
    result.matches.forEach { match in
        print("\(match.matchID): \(match.size)/10 players")
    }
} catch {
    debugPrint(error)
}

To find a match that has a label of "AnExactMatchLabel":

1
var label = "AnExactMatchLabel"

Advanced:

In order to use a more complex structured query, the match label must be in JSON format.

To find a match where it expects player skill level to be >100 and optionally has a game mode of "sabotage":

1
var label = "{\"skill\": 125, \"mode\": \"sabotage\"}"

Spawning players #

The match object has a list of current online users, known as presences.

Sagi-shi uses the match presences to spawn players on the client:

1
2
3
4
5
6
7
8
var match = try await socket.joinMatch(matchId: matchId)

var players = [String: GameObject]()

match.presences.forEach { presence in
    var go = spawnPlayer() // Instantiate player object
    players[presence.session.id] = go
}

Sagi-shi keeps the spawned players up-to-date as they leave and join the match using the match presence received event:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
socket.onmatchpresence = { matchPresenceEvent in
    // For each player that has joined in this event...
    matchPresenceEvent.joins.forEach { presence in
        // Spawn a player for this presence and store it in a dictionary by session id.
        var go = spawnPlayer() // Instantiate player object
        players[presence.session.id] = go
    }

    // For each player that has left in this event...
    matchPresenceEvent.leaves.forEach { presence in
        // Remove the player from the game if they've been spawned
        if players[presence.session.id] != nil {
            players[presence.session.id] = nil
        }
    }
}

Sending match state #

Nakama has real-time networking to send and receive match state as players move and interact with the game world.

During the match, each Sagi-shi client sends match state to the server to be relayed to the other clients.

Match state contains an op code that lets the receiver know what data is being received so they can deserialize it and update their view of the game.

Example op codes used in Sagi-shi:

  • 1: player position
  • 2: player calling vote

Sending player position

Define a class to represent Sagi-shi player position states:

1
2
3
4
5
class PositionState {
    static var X: Double = 0
    static var Y: Double = 0
    static var Z: Double = 0
}

Create an instance from the player’s transform, set the op code and send the JSON encoded state:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var state = PositionState() {
    X = transform.position.x,
    Y = transform.position.y,
    Z = transform.position.z
}

var opCode = 1

do {
    let messageAck = try await socket.sendMatchState(matchId: match.id, opCode: opCode, data: state)
    print("Match state sent successfully", messageAck)
} catch {
    debugPrint(error)
}

Op Codes as a static class

Sagi-shi has many networked game actions. Using a static class of constants for op codes will keep your code easier to follow and maintain:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class OpCodes {
    static var position = 1
    static var vote = 2
}

do {
    let messageAck = try await socket.sendMatchState(matchId: match.id, opCode: OpCodes.position, data: state)
    print("Match state sent successfully", messageAck)
} catch {
    debugPrint(error)
}

Receiving match state #

Sagi-shi players can receive match data from the other connected clients by subscribing to the match state received event:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
socket.onmatchdata = { matchState in
    switch matchState.opCode {
    case OpCodes.position:
        // Get the updated position data
        let stateJson = matchState.state
        let positionState = JSON.parse(stateJson)

        // Update the GameObject associated with that player
        if players[matchState.user_presence.session.id] != nil {
            // Here we would normally do something like smoothly interpolate to the new position, but for this example let's just set the position directly.
            players[matchState.user_presence.session.id].transform.position = new Vector3(positionState.s, positionState.y, positionState.z)
        }
    default:
        print("Unsupported op code")
    }
}

Matchmaker #

Developers can find matches for players using Match Listing or the Nakama Matchmaker, which enables players join the real-time matchmaking pool and be notified when they are matched with other players that match their specified criteria.

Matchmaking helps players find each other, it does not create a match. This decoupling is by design, allowing you to use matchmaking for more than finding a game match. For example, if you were building a social experience you could use matchmaking to find others to chat with.

Add matchmaker #

Matchmaking criteria can be simple, find 2 players, or more complex, find 2-10 players with a minimum skill level interested in a specific game mode.

Sagi-shi allows players to join the matchmaking pool and have the server match them with other players:

1
2
3
4
5
6
var minPlayers = 2
var maxPlayers = 10
var query = "+skill:>100 mode:sabotage"
var stringProperties = ["mode": "sabotage"]
var numericProperties = ["skill": 125]
var matchmakerTicket = try await socket.addMatchmaker(query: query, minCount: minPlayers, maxCount: maxPlayers, stringProperties: stringProperties, numericProperties: numericProperties)

After being successfully matched according to the provided criteria, players can join the match:

1
2
3
4
5
6
7
8
socket.onmatchmakermatched = { matchmakerMatched in
    do {
        let match = try await socket.joinMatch(matchmakerMatched)
        print("Joined match successfully", match)
    } catch {
        debugPrint(error)
    }
}

Parties #

Nakama Parties is a real-time system that allows players to form short lived parties that don’t persist after all players have disconnected.

Sagi-shi allows friends to form a party and matchmake together.

Creating parties #

The player who creates the party is the party’s leader. Parties have maximum number of players and can be open to automatically accept players or closed so that the party leader can accept incoming join requests.

Sagi-shi uses closed parties with a maximum of 4 players:

1
2
3
4
5
6
7
8
var open = false
var maxPlayers = 4
do {
    let party = try await socket.createParty(open: open, maxCount: maxPlayers)
    print("Party created successfully", party)
} catch {
    debugPrint(error)
}

Sagi-shi shares party ids with friends via private/direct messages:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var friendsList = try await client.listFriends(session: session)
var onlineFriends = friendsList.friends.filter { friend in
    return friend.user.online
}

onlineFriends.forEach { friend in
    var messageData = ["message": "Hey \(friend.username), wanna join the party?"]
    var partyId = party.id
    do {
        let channel = try await socket.joinChat(userId: friend.user.id, type: 2, persistence: true, hidden: false)
        let messageAck = try await socket.writeChatMessage(channelId: channel.id, data: messageData)
        print("Message sent successfully", messageAck)
    } catch {
        debugPrint(error)
    }
}

Joining parties #

Sagi-shi players can join parties from chat messages by checking for the party id in the message:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
socket.onchannelmessage = { channelMessage in
    let content = channelMessage.content as! [String: String]
    if content["partyId"] != nil {
        do {
            let party = try await socket.joinParty(partyId: content["partyId"]!)
            print("Joined party successfully", party)
        } catch {
            debugPrint(error)
        }
    }
}

Promoting a member #

Sagi-shi party members can be promoted to the party leader:

1
2
3
4
5
6
7
var newLeader = "<user id>"
do {
    try await socket.promotePartyMember(partyId: party.id, newLeader: newLeader)
    print("Party member promoted successfully")
} catch {
    debugPrint(error)
}

Leaving parties #

Sagi-shi players can leave parties:

1
2
3
4
5
6
do {
    try await socket.leaveParty(partyId: party.id)
    print("Party left successfully")
} catch {
    debugPrint(error)
}

Matchmaking with parties #

One of the main benefits of joining a party is that all the players can join the matchmaking pool together.

Sagi-shi players can listen to the the matchmaker matched event and join the match when one is found:

1
2
3
4
5
6
7
8
socket.onmatchmakermatched = { matchmakerMatched in
    do {
        let match = try await socket.joinMatch(matchmakerMatched)
        print("Joined match successfully", match)
    } catch {
        debugPrint(error)
    }
}

The party leader will start the matchmaking for their party:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var partyId = "<party id>"
var minPlayers = 2
var maxPlayers = 10
var query = ""

do {
    let matchmakerTicket = try await socket.addMatchmakerParty(partyId: partyId, query: query, minCount: minPlayers, maxCount: maxPlayers)
    print("Matchmaking ticket added successfully", matchmakerTicket)
} catch {
    debugPrint(error)
}

Sending party data #

Sagi-shi players can send data to other members of their party to indicate they wish to start a vote.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var state = [
    "username": "<Username>",
    "reason": "Emergency"
]

do {
    let messageAck = try await socket.sendPartyData(partyId: party.id, opCode: OpCodes.partyCallVote, data: state)
    print("Party data sent successfully", messageAck)
} catch {
    debugPrint(error)
}

Receiving party data #

Sagi-shi players can receive party data from other party members by subscribing to the party data event.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
socket.onpartydata = { partyData in
    switch partyData.opCode {
    case OpCodes.partyCallVote:
        // Get the vote data
        let stateJson = partyData.data
        let voteState = JSON.parse(stateJson)

        // Show a UI dialogue - "<username> has proposed to call a vote for <reason>. Do you agree? Yes/No"
    default:
        print("Unsupported op code")
    }
}

Leaderboards #

Nakama Leaderboards introduce a competitive aspect to your game and increase player engagement and retention.

Sagi-shi has a leaderboard of weekly imposter wins, where player scores increase each time they win, and similarly a leaderboard for weekly crew member wins.

Sagi-shi leaderboard screen
Sagi-shi Leaderboard

Creating leaderboards #

Leaderboards have to be created on the server, see the leaderboard documentation for details on creating leaderboards.

Submitting scores #

When players submit scores, Nakama will increment the player’s existing score by the submitted score value.

Along with the score value, Nakama also has a subscore, which can be used for ordering when the scores are the same.

Sagi-shi players can submit scores to the leaderboard with contextual metadata, like the map the score was achieved on:

1
2
3
4
5
6
7
8
9
var score = 1
var subscore = 0
var metadata = ["map": "space_station"]
do {
    let leaderboardRecord = try await client.writeLeaderboardRecord(session: session, leaderboardId: "weekly_imposter_wins", score: score, subscore: subscore, metadata: metadata)
    print("Leaderboard record written successfully", leaderboardRecord)
} catch {
    debugPrint(error)
}

Listing the top records #

Sagi-shi players can list the top records of the leaderboard:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var limit = 20
var leaderboardName = "weekly_imposter_wins"
do {
    let result = try await client.listLeaderboardRecords(session: session, leaderboardId: leaderboardName, ownerIds: nil, expiry: nil, limit: limit, cursor: nil)
    result.records.forEach { record in
        print("\(record.owner.id): \(record.score)")
    }
} catch {
    debugPrint(error)
}

Listing records around the user

Nakama allows developers to list leaderboard records around a player.

Sagi-shi gives players a snapshot of how they are doing against players around them:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var userId = session.user.id
var limit = 20
var leaderboardName = "weekly_imposter_wins"
do {
    let result = try await client.listLeaderboardRecordsAroundOwner(session: session, leaderboardId: leaderboardName, ownerId: userId, expiry: nil, limit: limit)
    result.records.forEach { record in
        print("\(record.owner.id): \(record.score)")
    }
} catch {
    debugPrint(error)
}

Listing records for a list of users

Sagi-shi players can get their friends’ scores by supplying their user ids to the owner id parameter:

1
2
3
4
5
6
7
8
9
var friendsList = try await client.listFriends(session: session)
var userIds = friendsList.friends.map { friend in
    return friend.user.id
}
var result = try await client.listLeaderboardRecords(session: session, leaderboardId: "weekly_imposter_wins", ownerIds: userIds, expiry: nil, limit: limit, cursor: nil)

result.records.forEach { record in
    print("\(record.owner.id): \(record.score)")
}

The same approach can be used to get group member’s scores by supplying their user ids to the owner id parameter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var groupId = "<groupId>"
var groupUserList = try await client.listGroupUsers(session: session, groupId: groupId)
var userIds = groupUserList.groupUsers.map { groupUser in
    return groupUser.user.id
}

var result = try await client.listLeaderboardRecords(session: session, leaderboardId: "weekly_imposter_wins", ownerIds: userIds, expiry: nil, limit: limit, cursor: nil)

result.records.forEach { record in
    print("\(record.owner.id): \(record.score)")
}

Deleting records #

Sagi-shi players can delete their own leaderboard records:

1
2
3
4
5
6
7
var leaderboardId = "<leaderboard id>"
do {
    try await client.deleteLeaderboardRecord(session: session, leaderboardId: leaderboardId)
    print("Leaderboard record deleted successfully")
} catch {
    debugPrint(error)
}

Tournaments #

Nakama Tournaments are short lived competitions where players compete for a prize.

Sagi-shi players can view, filter and join running tournaments.

Sagi-shi tournaments screen
Sagi-shi Tournaments

Creating tournaments #

Tournaments have to be created on the server, see the tournament documentation for details on how to create a tournament.

Sagi-shi has a weekly tournament which challenges players to get the most correct imposter votes. At the end of the week the top players receive a prize of in-game currency.

Joining tournaments #

By default in Nakama players don’t have to join tournaments before they can submit a score, but Sagi-shi makes this mandatory:

1
2
3
4
5
6
7
var tournamentId = "<tournament id>"
do {
    try await client.joinTournament(session: session, tournamentId: tournamentId)
    print("Tournament joined successfully")
} catch {
    debugPrint(error)
}

Listing tournaments #

Sagi-shi players can list and filter tournaments with various criteria:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var categoryStart = 1
var categoryEnd = 2
var startTime = 1538147711
var endTime = nil // all tournaments from the start time
var limit = 100 // number to list per page
var cursor = nil
do {
    let result = try await client.listTournaments(session: session, categoryStart: categoryStart, categoryEnd: categoryEnd, startTime: startTime, endTime: endTime, limit: limit, cursor: cursor)
    result.tournaments.forEach { tournament in
        print("\(tournament.id): \(tournament.title)")
    }
} catch {
    debugPrint(error)
}

For performance reasons categories are filtered using a range, not individual numbers. Structure your categories to take advantage of this (e.g. all PVE tournaments in the 1XX range, all PVP tournaments in the 2XX range, etc.).

Listing records #

Sagi-shi players can list tournament records:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var tournamentName = "weekly_top_detective"
var limit = 20

do {
    let result = try await client.listTournamentRecords(session: session, tournamentId: tournamentName, limit: limit)
    result.records.forEach { record in
        print("\(record.owner.id): \(record.score)")
    }
} catch {
    debugPrint(error)
}

Listing records around a user

Similarly to leaderboards, Sagi-shi players can get other player scores around them:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var userId = "<user id>"
var limit = 20
var tournamentName = "weekly_top_detective"

do {
    let result = try await client.listTournamentRecordsAroundOwner(session: session, tournamentId: tournamentName, ownerId: userId, limit: limit)
    result.records.forEach { record in
        print("\(record.owner.id): \(record.score)")
    }
} catch {
    debugPrint(error)
}

Submitting scores #

Sagi-shi players can submit scores, subscores and metadata to the tournament:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var tournamentName = "weekly_top_detective"
var score = 1
var subscore = 0
var metadata = ["map": "space_station"]

do {
    let tournamentRecord = try await client.writeTournamentRecord(session: session, tournamentId: tournamentName, score: score, subscore: subscore, metadata: metadata)
    print("Tournament record written successfully", tournamentRecord)
} catch {
    debugPrint(error)
}

Notifications #

Nakama Notifications can be used for the game server to broadcast real-time messages to players.

Notifications can be either persistent (remaining until a player has viewed it) or transient (received only if the player is currently online).

Sagi-shi uses Notifications to notify tournament winners about their winnings.

Sagi-shi notification screen
Sagi-shi notifications

Receiving notifications #

Notifications have to be sent from the server.

Nakama uses a code to differentiate notifications. Codes of 0 and below are system reserved for Nakama internals.

Sagi-shi players can subscribe to the notification received event. Sagi-shi uses a code of 100 for tournament winnings:

1
2
3
4
5
6
7
8
9
socket.onnotification = { notification in
    let rewardCode = 100
    switch notification.code {
    case rewardCode:
        print("Congratulations, you won the tournament!\n\(notification.subject)\n\(notification.content)")
    default:
        print("Other notification: \(notification.code):\(notification.subject)\n\(notification.content)")
    }
}

Listing notifications #

Sagi-shi players can list the notifications they received while offline:

1
2
3
4
5
6
7
var result = try await client.listNotifications(session: session, limit: limit, cacheableCursor: nil)

result.notifications.forEach { notification in
    print("Notification: \(notification.code):\(notification.subject)\n\(notification.content)")
}

print("Fetch more results with cursor:", result.cacheable_cursor)
1
2
3
4
5
6
7
var limit = 100
var cacheableCursor = result.cacheable_cursor
var nextResults = try await client.listNotifications(session: session, limit: limit, cacheableCursor: cacheableCursor)

nextResults.notifications.forEach { notification in
    print("Notification: \(notification.code):\(notification.subject)\n\(notification.content)")
}

Pagination and cacheable cursors

Like other listing methods, notification results can be paginated using a cursor or cacheable cursor from the result.

1
var cacheableCursor = result.cacheable_cursor;

The next time the player logs in the cacheable cursor can be used to list unread notifications.

1
var nextResults = try await client.listNotifications(session: session, limit: limit, cacheableCursor: cacheableCursor)

Deleting notifications #

1
2
3
4
5
6
7
var notificationId = "<notification id>"
do {
    try await client.deleteNotifications(session: session, ids: [notificationId])
    print("Notification deleted successfully")
} catch {
    debugPrint(error)
}