Skip to content

Zovube/react-native-game-center

 
 

Repository files navigation

react-native-game-center

Meet react-native-game-center

npm version npm version

React Native Game Center

app achivements leaderboard ifnotloggedin

Status

This is a fork of garrettmac/react-native-game-center. It contains some further work, as well as some refactoring. It is, however, a work in progress, and some features beyond simple login (leatherboards) may not work correctly in it's current state. Patches are welcome! It is not currently published on npm.

Contents

Installation

In your project root, run:

yarn add react-native-game-center
react-native link react-native-game-center

If you need help setting up GameCenter within iTunes Connect, see SETUP.md.

Example Project

You may want to clone this repo and play with the example project:

$ git clone https://github.com/miracle2k/react-native-game-center
$ cd react-native-game-center/GameCenterExample
$ yarn install
$ npm start

Basic Usage

import GameCenter from "react-native-game-center"


// The event handler will be called whenever the authentication status changes,
// and often, when it did not. For example, every time your app returns from
// the background, GameKit will call this, because the user may have logged out.
GameCenter.addListener('onAuthenticate', ({isAuthenticated}) => {
  if (!isAuthenticated) {
    Logout();
  }  
});


// There are two ways to get started:


// The init method will check if the user is already logged in, and if so, the
// user will see a "Welcome back" message from GameCenter. The promise will 
// tell if whether they are or are not authenticated.
//
// If they are, you can then do things like call `getPlayer()`.
      
GameCenter.init().then(({isAuthenticated}) => {
  ...
});


// The authenticate method can be called in addition or instead of "init": It
// will, if the user is not logged in, show the GameCenter login screen.

init() <Promise?>

Initializes GameCenter functionality, and immediately tries to see if the current user is already logged into your app. If so, GameKit will show a "Welcome back" message. If the user is not yet authenticated, you can call authenticate() to show the login screen.

GameCenter.init()
  .then(console.log)
  .catch(console.warn)

authenticate() <Promise?>

Same as init(), but will show a GameCenter login screen if the user is not yet authorized.

GameCenter.authenticate()
  .then(console.log)
  .catch(console.warn)

Player Methods

Player Methods

getPlayer <Promise?>

Returns the authenticated user, or null if no user is authenticated.

Basic Usage

  GameCenter.getPlayer().then(player=>{
      console.log("player: ", player);
  })

Response

{alias: "Garrettmacmac", displayName: "Me", playerID: "G:8135064222"}

getPlayerImage <Promise?>

Details

Gets logged player image if available. Most players don't have one.

Parameters

No Parameters

Usage

  GameCenter.getPlayerImage().then(image=>{
      console.log("image: ", image);
  })

Success Response

{image: "/path/to/image.png"}

Failed Response

Error fetching player image

getPlayerFriends

Details

Gets a list of players. Most games don't have this anymore as Apple took away the game center App. Now you see lots of users connect via Facebook, SMS and by geolocation.

Parameters

No Parameters

Usage

  GameCenter.getPlayerFriends().then(friends=>{
      console.log("friends: ", friends);
  })

Response

I don't know what this looks like, as I don't have friends 😫 and Apple said they are depreciating support for this is new versions.

Success

[...array of friends]

or

undefined

Failed

Error fetching player friends

Leaderboard Methods

openLeaderboardModal <Promise?>

Details

Opens Game Center Modal on Leaderboard Page

Parameters

No Parameters

Usage

  GameCenter.openLeaderboardModal()
  .then(success=>{})//is open
  .catch(error=>{})//could not open

Success Response

opened leaderboard modal

Failed Response

opened leaderboard modal

submitLeaderboardScore <Promise?>

Details

Submit progress of users leaderboard

Parameters

Name Required Default Description
score Yes n/a some number to track for leaderboard
leaderboardIdentifier No* (see Response) leaderboardIdentifier set up in Itunes Connect

Usage

Basic

let options={score:50};

//reverts to default leaderboardIdentifier set up in init()
GameCenter.submitLeaderboardScore(options)
//now update state
this.setState(options)

Advanced

let options={
  score:50,
  leaderboardIdentifier:"some_other_leaderboard"
};

GameCenter.submitLeaderboardScore(options)
  .then(res=>{
    if(res==="Successfully submitted score")
          this.setState({score:50})
  })
  .catch(console.warn("Users progress is not being tracked due to error."))

Response

Success

"Successfully submitted score"

Failed

"Error submitting score."

getLeaderboardPlayers <Promise?>

Details

Get information about certain player ids on the leaderboard

Parameters

Name Required Default Description
playerIds[] Yes n/a An array of player ids to recieve data for
leaderboardIdentifier No if set in init Set in init leaderboardIdentifier set up in Itunes Connect

Usage

Basic

let options={
  playerIds: ["player_1","player_2"], //Please note that this is the player id as set by apple and not the user name
  leaderboardIdentifier:"some_other_leaderboard" //Optional
};

GameCenter.getLeaderboardPlayers(options)
  .then(res=>{
    this.setState({players:res})
  })
  .catch(console.warn("Leaderboard fetch failed"))

Response

Success

[
  {
    "rank":"rank of player on global leaderboard",
    "value":"score of the player on the leaderboard",
    "displayName":"display name of the player",
    "alias":"alias of the player",
    "playerID":"id of the player"
  }
]

Failed

"Error getting leaderboard players."

getTopLeaderboardPlayers <Promise?>

Details

Get information about top players on the leaderboard

Parameters

Name Required Default Description
count Yes n/a Anmount of top players to fetch
leaderboardIdentifier No if set in init Set in init leaderboardIdentifier set up in Itunes Connect

Usage

Basic

let options={
  count:4,
  leaderboardIdentifier:"some_other_leaderboard" //Optional
};

GameCenter.getLeaderboardPlayers(options)
  .then(res=>{
    this.setState({topPlayers:res})
  })
  .catch(console.warn("Leaderboard fetch failed"))

Response

Success

[
  {
    "rank":"rank of player on global leaderboard",
    "value":"score of the player on the leaderboard",
    "displayName":"display name of the player",
    "alias":"alias of the player",
    "playerID":"id of the player"
  }
]

Failed

"Error getting top leaderboard players."

Achievements Methods

openAchievementModal <Promise?>

Details

Opens Game Center Modal on Leaderboard Page

Parameters

No Parameters

Usage

  GameCenter.openAchievementModal()
  .then(success=>{})//is open
  .catch(error=>{})//could not open

Response

Success

opened achievement modal

Failed

opened achievement modal

getAchievements <Promise?>

Details

Gets players achievements if completed more than 0%. You must declare submitAchievementScore at least once before calling this.

Parameters

No Parameters

Usage

  GameCenter.getAchievements()
  .then(achievements=>{
    console.log(achievements)
    })
  .catch(error=>{})//failed

Response

[{"showsCompletionBanner":false,"lastReportedDate":1506301241432,"completed":true,"percentComplete":100,"identifier":"novice_award"},{"showsCompletionBanner":false,"lastReportedDate":1506301211362,"completed":false,"percentComplete":5,"identifier":"pro_award"}]

or

[]

resetAchievements <Promise?>

[Reset Achievements]

Details

Resets the players achievements.

Parameters

Name Required Default Description
hideAlert No {hideAlert:false} Hide reset confirmation prompt

Usage

Basic

  //Triggers confirmation prompt
  GameCenter.resetAchievements()

  // hides confirmation prompt
  GameCenter.resetAchievements({hideAlert:true})

Advanced

  GameCenter.resetAchievements(res=>{
    if(res.resetAchievements){
      do something if user reset achievements
    }
  })
  .catch(alert("Could not reset achievements at this time. Try again later."))

Response

If you pass in {hideAlert:true} into GameCenter.resetAchievements() Method OR the you don't pass in the hideAlert parameter and player presses "Reset"

{"resetAchievements":true,"message":"User achievements reset"}

If you don't pass in the hideAlert parameter and player presses "No!"

{"resetAchievements":false,"message":"User achievements not reset"}

submitAchievementScore <Promise?>

Details

Submit progress of users achievements

Parameters

Name Required Default Description
percentComplete Yes n/a number, float, or string of the percent achievement is complete. Range 1-100
achievementIdentifier No* (see Response) achievementIdentifier set up in Itunes Connect
hideCompletionBanner No false Hides Game center banner when complete

Usage

let options={
            percentComplete:50,
            achievementIdentifier:"novice_award"
          };

GameCenter.submitAchievementScore(options).then(res=>{
  if(res){
//success
  }
})
.catch(alert("Could not update your achievements at this time. Try again later."))

Response

Success

[null]

Not required if achievementIdentifier set as default in init(). achievementIdentifier always reverts to default unless defended. However, will reject promise if not passed in init() or submitAchievementScore() function

Failed

No Game Center `achievementIdentifier` passed and no default set

TODO

ADD METHODS

[ ] getLeaderboardPlayers() [ ] invite() [ ] challengeComposer() [ ] findScoresOfFriendsToChallenge()

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Objective-C 83.2%
  • JavaScript 15.9%
  • Ruby 0.9%