Monday, 2 September 2013

Game Kit Authentication


  • Documentation

Read Me About GKAuthentication
=================================================================
GKAuthentication is a sample application that shows how to correctly 
perform GameKit Authentication. This code is completely copy and paste-able.


IMPORTANT: When adding support for Game Center to an application, it is not
enough to simply add the necessary code to your application.  You also
need to configure your app in iTunes Connect to match your desired
configuration.  

=================================================================
BUILD REQUIREMENTS:

This project was built with Xcode 3.2.4 and iOS SDK 4.2

=================================================================
RUNTIME REQUIREMENTS:

The project requires iOS 4.2 and a GameCenter account to run.

=================================================================
PACKAGING LIST:
- ReadMe.txt -- This file.
- GKAuthentication.xcodeproj --  Xcode project for this sample. 
- Resources -- The project nib, images, and so on.
- Classes/GKAuthenticationAppDelegate.h -- Declaration of the best 
    practices
- Classes/GKAuthenticationAppDelegate.m -- Contains the best practices of 
    adding authentication to a project. 
- main.m -- The main function of this sample.


=================================================================
Copyright (C) 2011 Apple Inc. All rights reserved.



  • Design






  • Code

GKAuthenticationAppDelegate.h

Copyright (C) 2011 Apple Inc. All Rights Reserved.

 */

#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>

// Preferred method for testing for Game Center 
BOOL isGameCenterAvailable();


@class MainViewController;

@interface GKAuthenticationAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    UIViewController *mainViewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UIViewController *mainViewController;

// currentPlayerID is the value of the playerID last time GameKit authenticated.
@property (retain,readwrite) NSString * currentPlayerID;

// isGameCenterAuthenticationComplete is set after authentication, and authenticateWithCompletionHandler's completionHandler block has been run. It is unset when the applicaiton is backgrounded. 
@property (readwrite, getter=isGameCenterAuthenticationComplete) BOOL gameCenterAuthenticationComplete;

@end


----------------------------------------------------------------

GKAuthenticationAppDelegate.m


#include <sys/types.h>
#include <sys/sysctl.h>

#import "GKAuthenticationAppDelegate.h"


@implementation GKAuthenticationAppDelegate


@synthesize window;
@synthesize mainViewController;


#pragma mark -
#pragma mark Game Center Support

@synthesize currentPlayerID, 
            gameCenterAuthenticationComplete;



#pragma mark -
#pragma mark Game Center Support

// Check for the availability of Game Center API. 
BOOL isGameCenterAPIAvailable()
{
    // Check for presence of GKLocalPlayer API.
    Class gcClass = (NSClassFromString(@"GKLocalPlayer"));
    
    // The device must be running running iOS 4.1 or later.
    NSString *reqSysVer = @"4.1";
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);
    
    return (gcClass && osVersionSupported); 
}

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
{        
    // Override point for customization after application launch.  

    // Add the main view controller's view to the window and display.
    [self.window addSubview:mainViewController.view];
    [self.window makeKeyAndVisible];
    
    self.gameCenterAuthenticationComplete = NO;
    
    if (!isGameCenterAPIAvailable()) {
        // Game Center is not available. 
        self.gameCenterAuthenticationComplete = NO;
    } else {
        
        GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
        
        /*
         The authenticateWithCompletionHandler method is like all completion handler methods and runs a block
         of code after completing its task. The difference with this method is that it does not release the 
         completion handler after calling it. Whenever your application returns to the foreground after 
         running in the background, Game Kit re-authenticates the user and calls the retained completion 
         handler. This means the authenticateWithCompletionHandler: method only needs to be called once each 
         time your application is launched. This is the reason the sample authenticates in the application 
         delegate's application:didFinishLaunchingWithOptions: method instead of in the view controller's 
         viewDidLoad method.
         
         Remember this call returns immediately, before the user is authenticated. This is because it uses 
         Grand Central Dispatch to call the block asynchronously once authentication completes.
         */
        [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) {
            // If there is an error, do not assume local player is not authenticated. 
            if (localPlayer.isAuthenticated) {
                
                // Enable Game Center Functionality 
                self.gameCenterAuthenticationComplete = YES;

                if (! self.currentPlayerID || ! [self.currentPlayerID isEqualToString:localPlayer.playerID]) {

                    // Current playerID has changed. Create/Load a game state around the new user. 
                    self.currentPlayerID = localPlayer.playerID;
                    
                    // Load game instance for new current player, if none exists create a new.
                }
            } else {     
                // No user is logged into Game Center, run without Game Center support or user interface. 
                self.gameCenterAuthenticationComplete = NO;
            }
        }];
    }    
    
    // The user is not authenticated until the Completion Handler block is called. 
    return YES;
}

    

- (void)applicationDidEnterBackground:(UIApplication *)application  
{
    /*
     Invalidate Game Center GKAuthentication and save game state, so the game doesn't start until the GKAuthentication 
     Completion Handler is run. This prevents a new user from using the old users game state.
     */
    self.gameCenterAuthenticationComplete = NO;
}


/*
- (void)applicationWillEnterForeground:(UIApplication *)application  
{
    // Do not call authenticateWithCompletionHandler again here.Once you have set the CompletionHandler in the 
    // original call in application:didFinishLaunchingWithOptions, it will dispatch the block next time the 
    // application enters foreground. 
}
*/



#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application  
{
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc 
{
    [currentPlayerID release];
    [mainViewController release];
    [window release];
    [super dealloc];
}

@end

----------------------------------------------------------------


No comments:

Post a Comment