is it possible in iOS get Game Center id or account? - ios

I wan't use iOS GameCenter id to my own server id.
like google plus.
Is there any method to get game center id or account?
I have searched in internet this method. but it's return nil.
let player = GKLocalPlayer.localPlayer()
player.playerID, player.displayName
playerID is nil and displayName is Me
I want uniqe key is it possible?

func authenticateLocalPlayer() {
var localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(viewController : UIViewController!, error : NSError!) -> Void in
if viewController != nil {
self.presentViewController(viewController, animated: true, completion: nil)
}
else {
if localPlayer.authenticated {
self.gameCenterEnabled = true
localPlayer.loadDefaultLeaderboardIdentifierWithCompletionHandler({ (leaderboardIdentifier : String!, error : NSError!) -> Void in
if error != nil {
println(error.localizedDescription)
} else {
self.leaderboardIdentifier = leaderboardIdentifier
***above is your Game Center id***
}
})
} else {
self.gameCenterEnabled = false
}
}
}
}
In above code there self.leaderboardIdentifier is game centre id

Related

How to display Leaderboard Sets in iOS

I was trying to get this to work all last night but it wouldnt. Can anyone help?
I use the following code to display a leaderboard:
gameCenterViewController.leaderboardIdentifier = leaderboardId
This works fine for normal leaderboards, but fails to load any leaderboard sets, when I use the leaderboardSetId. Can you link directly to leaderboard sets and if so how do you do this?
Thanks.
Please do refer below code and cross verify your configuration.
Hope this would help you.
import GameKit
class YourViewController: UIViewController, GKGameCenterControllerDelegate {
var gcEnabled = Bool() // Stores if the user has Game Center enabled
var gcDefaultLeaderBoard = String() // Stores the default leaderboardID
override func viewDidLoad() {
super.viewDidLoad()
self.authenticateLocalPlayer()
}
func authenticateLocalPlayer()
{
let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(ViewController, error) -> Void in
if((ViewController) != nil) {
// 1 Show login if player is not logged in
self.presentViewController(ViewController!, animated: true, completion: nil)
} else if (localPlayer.authenticated) {
// 2 Player is already euthenticated & logged in, load game center
self.gcEnabled = true
// Get the default leaderboard ID
localPlayer.loadDefaultLeaderboardIdentifierWithCompletionHandler({ (leaderboardIdentifer: String?, error: NSError?) -> Void in
if error != nil {
print(error)
} else {
self.gcDefaultLeaderBoard = leaderboardIdentifer!
}
})
} else {
// 3 Game center is not enabled on the users device
self.gcEnabled = false
print("Local player could not be authenticated, disabling game center")
print(error)
}
}
}
#IBAction func clickToLeaderBoard(sender: UIButton) {
let gcVC: GKGameCenterViewController = GKGameCenterViewController()
gcVC.gameCenterDelegate = self
gcVC.viewState = GKGameCenterViewControllerState.Leaderboards
gcVC.leaderboardIdentifier = "YourLeaderboardId"
self.presentViewController(gcVC, animated: true, completion: nil)
}
func saveScoreOnGameCenter()
{
let leaderboardID = "YourLeaderboardId"
let sScore = GKScore(leaderboardIdentifier: leaderboardID)
sScore.value = Int64(10)
GKScore.reportScores([sScore], withCompletionHandler: { (error: NSError?) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
print("Score submitted")
}
})
}
func gameCenterViewControllerDidFinish(gcViewController: GKGameCenterViewController)
{
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Update
Also please do check your leaderboard configuration from back end.
Some good posts are here.
http://www.appcoda.com/ios-game-kit-framework/
https://developer.apple.com/game-center/
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/GameKit_Guide/GameCenterOverview/GameCenterOverview.html
Having ensured that you have authenticated the local player and your leaderboards set in iTunes Connect, you will need to report your scores to GameCenter ensuring you use 64bit Int.
Now you can add this to display the leaderboard for the local player:
func showGKGameCenterViewController(_ viewController: UIViewController) {
if gameCenterIsDisabled {
print("Local player is not authenticated")
}
let gameCenterViewController = GKGameCenterViewController()
gameCenterViewController.delegate = self
gameCenterViewController.viewState = GKGameCenterViewControllerState.default
viewController.presentViewController(gameCenterViewController, animated: true, completion: nil)
}

Facebook Login Swift

I wrote a basic Swift Class for Facebook login handling.
I want to check if the user already authorised the App, because in my case, the user gets asked everytime if he authorises the app - it switches to safari everytime instead of simply logging in. Sometimes the login completely fails - no error message, but also no success.
Here is my code:
class FacebookLogin{
private var data : NSMutableData? = nil
init(){
}
let facebookReadPermissions = ["public_profile", "email", "user_friends"]
func loginToFacebookWithSuccess(successBlock: () -> (), andFailure failureBlock: (NSError?) -> ()) {
if FBSDKAccessToken.currentAccessToken() != nil {
return
}
FBSDKLoginManager().logInWithReadPermissions(self.facebookReadPermissions, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
if error != nil {
// Process error
FBSDKLoginManager().logOut()
failureBlock(error)
} else if result.isCancelled {
// Handle cancellations
FBSDKLoginManager().logOut()
failureBlock(nil)
} else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
var allPermsGranted = true
let grantedPermissions = Array(result.grantedPermissions).map( {"\($0)"} )
for permission in self.facebookReadPermissions {
if !contains(grantedPermissions, permission) {
allPermsGranted = false
break
}
}
if allPermsGranted {
// Do work
let fbToken = result.token.tokenString
let fbUserID = result.token.userID
println(fbUserID)
successBlock()
} else {
//The user did not grant all permissions requested
failureBlock(nil)
}
}
})
}
func login() -> Void{
if(self.alreadyLoggedIn() == false){
self.performLogin()
}else{
self.getFBUserData()
}
}
private func performLogin() -> Void {
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager();
fbLoginManager.loginBehavior = FBSDKLoginBehavior.SystemAccount
println(FBSDKAccessToken.currentAccessToken())
fbLoginManager.logInWithReadPermissions(["email"], handler: { (result, error) -> Void in
if (error == nil){
var fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
fbLoginManager.logOut()
}
}
})
}
private func alreadyLoggedIn() -> Bool {
if (FBSDKAccessToken.currentAccessToken() != nil)
{
return true
}else{
return false
}
}
private func getFBUserData() -> Void{
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
}
})
}
}
}
Thanks
In your view controller viewDidLoad() you can add this code :
if (FBSDKAccessToken.currentAccessToken() == nil)
{
// User is not already logged
println("No Logged")
}
else
{
// User is already logged
println("Already Logged")
}

Game Center Leaderboard: new score doesn't show up instantly

I have the following code which reports score and also displays leaderboard. Everything seems to be okay but when I send it new updated score, it doesn't show the score on leaderboard unless I click on Challenges tab or All Time. Basically, it needs me to click on something else inside leaderboard so the leaderboard can refresh and display the most recent score.
func reportLeaderboardIdentifier(identifier: String, score: Int) {
let scoreObject = GKScore(leaderboardIdentifier: identifier)
scoreObject.value = Int64(score)
GKScore.reportScores([scoreObject]) { (error) -> Void in
if error != nil {
println("Error in reporting leaderboard scores: \(error)")
}
}
}
func displayLeaderboard () {
var gameCenterController: GKGameCenterViewController = GKGameCenterViewController()
gameCenterController.viewState = GKGameCenterViewControllerState.Leaderboards
gameCenterController.gameCenterDelegate = self
self.vc.presentViewController(gameCenterController, animated: true , completion:nil)
}
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) {
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}

Game Center log-in window never appearing

The problem here is that the player is not getting authenticated and I'm not getting the log-in window for game center so I really need to get this fixed as soon as possible.
func authenticateLocalPlayer() {
var localPLayer = GKLocalPlayer.localPlayer()
localPLayer.authenticateHandler = {(viewController : UIViewController!, error : NSError!) -> Void in
if viewController != nil {
self.presentViewController(viewController, animated: true, completion: nil)
} else {
if localPLayer.authenticated {
self.gameCenterEnabled = true
localPLayer.loadDefaultLeaderboardIdentifierWithCompletionHandler({ (leaderboardIdentifier : String!, error : NSError!) -> Void in
if error != nil {
println(error.localizedDescription)
} else {
self.leaderboardIdentifier = leaderboardIdentifier
}
})
} else {
self.gameCenterEnabled = false
}
}
}
}

Gamecenter "Welcome"-Banner not showing up

I have a problem with Gamecenter. Actually I don't know if its really a problem.
After authenticating my localPlayer the "Welcome"-Banner does not show up.
Why is that? Is that a sign that something is wrong?
I wrote my first app with Swift and SpriteKit with Gamecenter integration. When I open my app, Gamecenter authenticates my localPlayer just fine.
GKLocalPlayer.localPlayer().authenticated // is true
Opening up the Leaderboard works fine too. If I log out of Gamecenter and open my App again it asks me to log in with the view Gamecenter provides.
Showing a GKNotification is also no problem. Pops up right away.
This is my code to authenticate the player:
func authenticateLocalPlayer(){
var localPlayer = GKLocalPlayer()
localPlayer.authenticateHandler = {(viewController, error) -> Void in
if ((viewController) != nil) {
self.presentViewController(viewController, animated: true, completion: nil)
}else{
println("(GameCenter) Player authenticated: \(GKLocalPlayer.localPlayer().authenticated)")
}
}
}
What am I missing?
I'm using this to authenticate with Game Center, and I had never a problem with it (always a welcome banner):
func authenticateLocalPlayer() {
let localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler =
{ (viewController : UIViewController?, error : NSError?) -> Void in
if viewController != nil
{
self.presentViewController(viewController!, animated:true, completion: nil)
}
else
{
if localPlayer.authenticated
{
print("Player authenticated")
self.gameCenterEnabled = true
isAuthenticated = true
localPlayer.loadDefaultLeaderboardIdentifierWithCompletionHandler
{ (leaderboardIdentifier, error) -> Void in
if error != nil
{
print("error", appendNewline: false)
}
else
{
self.leaderboardIdentifier = leaderboardIdentifier
print("\(self.leaderboardIdentifier)")
}
}
} else {
print("Not able to authenticate")
self.gameCenterEnabled = false
if error != nil
{
print("\(error!.description)")
}
else
{
print("error is nil")
}
}
}
}
}

Resources