This answer partially carries off on where we left off in the comments, since you didn't post your entire code I can't tell exactly where your hangup was, but this is what I put together along with a separate guide (it's a slightly different version of the code you post):
Author of most of the code:
https://www.reddit.com/r/swift/comments/3q5owv/how_to_add_a_leaderboard_in_spritekit_and_swift_20/
GameViewController.swift:
import UIKit
import SpriteKit
import GameKit
class GameViewController: UIViewController {
func authenticateLocalPlayer() {
let localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(viewController, error) -> Void in
if (viewController != nil) {
self.presentViewController(viewController!, animated: true, completion: nil)
}
else {
print((GKLocalPlayer.localPlayer().authenticated))
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
/////authentication//////
authenticateLocalPlayer()
//... The rest of the default code
}
//... The rest of the default code
}
GameScene.swift (or whichever scene you want to use GC):
import SpriteKit
import GameKit
import UIKit
// Global scope (I generally put these in a new file called Global.swift)
var score = 0
//sends the highest score to leaderboard
func saveHighscore(gameScore: Int) {
print ("You have a high score!")
print("\n Attempting to authenticating with GC...")
if GKLocalPlayer.localPlayer().authenticated {
print("\n Success! Sending highscore of \(score) to leaderboard")
//---------PUT YOUR ID HERE:
// |
// |
// V
let my_leaderboard_id = "YOUR_LEADERBOARD_ID"
let scoreReporter = GKScore(leaderboardIdentifier: my_leaderboard_id)
scoreReporter.value = Int64(gameScore)
let scoreArray: [GKScore] = [scoreReporter]
GKScore.reportScores(scoreArray, withCompletionHandler: {error -> Void in
if error != nil {
print("An error has occured:")
print("\n \(error) \n")
}
})
}
}
// Your scene:
class GameScene: SKScene, GKGameCenterControllerDelegate {
// Local scope variables (for this scene):
// Declare a new node, then initialize it
let call_gc_node = SKLabelNode(fontNamed:"Chalkduster")
let add_score_node = SKLabelNode(fontNamed: "Helvetica")
override func didMoveToView(view: SKView) {
// Give our GameCenter node some stuff
initGCNode: do {
// Set the name of the node (we will reference this later)
call_gc_node.name = "callGC"
// Default inits
call_gc_node.text = "Send your HighScore of \(score) into Game Center"
call_gc_node.fontSize = 25
call_gc_node.position = CGPoint(
x:CGRectGetMidX(self.frame),
y:CGRectGetMidY(self.frame))
// Self here is the instance (object) of our class, GameScene
// This adds it to our view
self.addChild(call_gc_node)
}
// Give our Add label some stuff
initADDLabel: do {
// Set the name of the node (we will reference this later)
add_score_node.name = "addGC"
// Basic inits
add_score_node.text = "ADD TO SCORE!"
add_score_node.fontSize = 25
add_score_node.position = call_gc_node.position
// Align our label some
add_score_node.runAction(SKAction.moveByX(0, y: 50, duration: 0.01))
// Add it to the view
self.addChild(add_score_node)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
// Get the position of our click
let TPOINT = touch.locationInNode(self)
// Get the name (string) of the node that was touched
let
node_that_was_touched: String?
= nodeAtPoint(TPOINT).name
// Prepare for switch statement, when we unwrap the optional, we don't want nil
guard (node_that_was_touched != nil)
else { print("-> before switch: found nil--not entering Switch");
return
}
// Find out which node we clicked based on node.name?, then do stuff:
switch node_that_was_touched! {
case "callGC":
// We clicked the GC label:
GameOver: do {
print("GAME OVER!")
// If we have a high-score, send it to leaderboard:
overrideHighestScore(score)
// Reset our score (for the next playthrough)
score = 0
// Show us our stuff!
showLeader()
}
case "addGC":
// we clicked the Add label:
// Update our *current score*
score += 1
default: print("no matches found")
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
call_gc_node.text = "Send your HighScore of \(score) into Game Center"
}
// Gamecenter
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
//shows leaderboard screen
func showLeader() {
let viewControllerVar = self.view?.window?.rootViewController
let gKGCViewController = GKGameCenterViewController()
gKGCViewController.gameCenterDelegate = self
viewControllerVar?.presentViewController(gKGCViewController, animated: true, completion: nil)
}
// Your "game over" function call
func overrideHighestScore(gameScore: Int) {
NSUserDefaults.standardUserDefaults().integerForKey("highscore")
if gameScore > NSUserDefaults.standardUserDefaults().integerForKey("highscore")
{
NSUserDefaults.standardUserDefaults().setInteger(gameScore, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
saveHighscore(gameScore)
}
}
}
Pay special attention to
29: let my_leaderboard_id = "YOUR_LEADERBOARD_ID"
I put some silly ASCII art in there to make sure you don't miss it. You have to put in your actual leaderboard ID from the GameCenter set-up.
You have to add the GameCenter library as well, and do the iTunes connect to actually see your highscores in the pop-up window.
I think your initial problems were with not understanding some of the back-end of how SpriteKit and even iOS views work (which is totally fine, because Apple makes jumping in and making stuff very easy). But, as you see, following guides / tutorials can be difficult since your implementation will vary.
Here is some good info to start with:
Diagram of what happens each frame in SK:
So you see, the SKScene is the class with all of the fun stuff like Nodes and Actions, and is where everything (important to you) happens. You can generate these scenes through the Editor, but then you probably need to make a new .swift file to go with it (as each scene can have its own logic).
The editor is just a 'shortcut' to initializing a bunch of stuff, and honestly, you can make complete games with little code (but you very quickly find out that you want more)
So in this code, where you declare GameScene or PauseScreen (which are basically just class declarations, that inherit from SKScene), you quickly find this line talking about something that ISNT a scene:
override func didMoveToView(view: SKView)
.. it's calling a SKView... what is that, and where did it come from?
(Read about SKView here, and look at its inheritance):
https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKView/index.html#//apple_ref/occ/cl/SKView
We find this SKView declaration in the GameViewController
file, (which is just a class), notice that it's the same as the regular iOS apps mostly, as it inherits UIViewController:
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
Again, that method is declared in GameViewController.swift, which is basically just this:
class GameViewController: UIViewController
So how does all of this relate to iOS apps and SpriteKit? Well, they are all mashed on top of each other:
IOS app anatomy:
Basically, from right to left, you have the Window, which is (correct me if wrong) the AppDelegate, then the ViewController, then your View, which has all of the cool stuff in it (Storyboards sit inside of the View, just as SKScenes sit inside of the View.... Labels, Nodes, or Buttons, all sit inside of their respective classes ((the view)))
It's all a big sandwich of inheritance.
Check out the Apple websites for more info.
https://developer.apple.com/library/safari/documentation/UserExperience/Conceptual/MobileHIG/ContentViews.html#//apple_ref/doc/uid/TP40006556-CH13-SW1
https://developer.apple.com/spritekit/
https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SpriteKitFramework_Ref/
https://developer.apple.com/library/safari/documentation/UserExperience/Conceptual/MobileHIG/Anatomy.html
Basically, everything is an Class inherited from a class inherited from a class and so on, so on... It can get messy. You can also see these inheritances in Xcode by CMD+clicking on them, which will jump you to the source file.
Goodluck with your studies and adventures in SpriteKit :)
GameViewController
(Like in Jared's single view tutorial) and putting the logic in one of manySKScene
's. Unless this has to go throughGameViewController
and that manages all the scenes? Ultimately, I'm trying to save & retrieve GC data when the user taps a label in the given scene (GameOverScene
). – IrremissibleGameViewController
, then you need to post that as well. I think this may just be a scope issue, but it should work if you put the funcs in your labels correctly. – RibbleGameViewController
but I wanted to know how I could handle it through aSKScene
such asGameOverScene
. Rather than his UIButtons, I am using a label for calling the functions. Any suggestions would be great! – IrremissibleGameOverScene
. I have already passed the user score to this scene to display it in a label, but the score should also be saved to the leaderboard (GameCenter) when entering this scene and the user should have the option of viewing it within this scene. Thanks again! – Irremissible