Click here to Skip to main content
15,887,881 members
Articles / Mobile Apps / iPhone

How To: Initialize a Game on iOS (iPhone/iPad) with XPG

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
26 Jan 2012CPOL5 min read 22.1K   5  
How to initialize a game on iOS (iPhone/iPad) with XPG

This is a continuation of the How To series. This first post is here.

This article will cover:

  • Adding the XPG Live API for iOS to your projects as a framework in XCode
  • Adding the XPG Live API for MonoTouch reference in MonoDevelop
  • Initializing the XPG Live API in code
  • Handling the initialization response

Prerequisites:

Adding the XPG Live API for iOS as a framework to your project in XCode

For the sake of simplicity, and because the source code is freely available, we’ll use the XPG Demo Source for iOS. We’ve also installed the stable release of the XPG Live API for iOS.

  1. In the XCode project navigator, select the top “Project” node
  2. With your target selected in the editor, click the “Build Phases” tab at the top of the editor
  3. Expand the “Link Binary With Libraries” section:

    image

  4. Click the “+” button under the list of libraries to open the library chooser:

    image

  5. Click the “Add Other…” button to open the finder browse dialog and navigate to “/Developer/XPG/APIs” and select “XPGLive.framework”:

    image

  6. Click “Open” to add the framework to your project.

Now your project is setup to use XPG Live.

XCode may show the framework in the project root. You can drag this down into the “Frameworks” group for better organization.

Adding the XPG Live API for MonoTouch reference in MonoDevelop

For the sake of simplicity, and because the source code is freely available, we’ll use the XPG Demo Source for MonoTouch. We’ve also installed the stable release of the XPG Live API for MonoTouch.

  1. Right click the “References” node in your project and select the “Edit References…” option:

    image

  2. Click the “.NET Assembly” tab and navigate to “/Developer/XPG/APIs
  3. Select “XPG.iOS.dll” and click “Add”:

    image

  4. Click “OK” to dismiss the window.

Now your project is setup to use XPG Live.

Initializing the XPG Live API in Code

Game initialization is very simple, but does require that you’re registered a free developer account on XPG Live, create a game and activate your first access key. Since we’re using the demo app, we’ve already completed those steps. The first post of this series gives a walk through of the management app and covers games and access keys.

Objective-C Code
C++
static NSString* _secretKey = @"DEMOKEY000000001";

-(void)viewDidLoad
{
    [super viewDidLoad];

    [XPGAPI initializeWith:_secretKey andCallback:nil];
    // Could have also used...
    // [XPGAPI initializeWith:_secretKey andCallback:self];
}
C# Code
C#
private static string _secretKey = @"DEMOKEY000000001";

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();

    XPGAPI.Instance.Initialize (_secretKey, null);
}

This will initialize your game locally unless you haven’t enabled iOS as a platform, you fat fingered the access key, or you forgot to activate the access key for your game. In one of these cases you’ll get back a localized failure response.

Handling the Initialization Response

The XPG Live API for iOS is pretty flexible when it comes to event handling. In .NET, you can handle events on a per call basis with anonymous delegates, delegate method references, or you can wire up event handler to the API instance. In Objective-C, you can implement the protocol on a single class and assign it as the API’s delegate, or you can implement the handled methods of the protocol in each class that needs to be notified and pass “self” as the callback parameter of the API methods. The Objective-C protocol defines all methods as optional, so implement what you need and don’t worry about the rest. The API will only invoke one callback per request. If a delegate was provided in the call, then it will be invoked, if the delegate passed was null/nil, then the API instance event will be raised if there is one.

Additionally, the API will raise events on the UI thread by default. This is done to protect against accidental cross thread access of UI components. The XPG Live API for iOS DOES NOT directly interact with UI components with the exception of social logins which will be discussed in a later post. You can choose to have your delegate raised on a background thread to keep your main thread free for drawing and updates with the following code:

Objective-C Code
C++
[XPGAPI callbackOnUIThread:NO];
C# Code
C#
XPGAPI.Instance.UseUIThreadEvents = false;

If you choose to handle callbacks on background threads, it is your responsibility to manage your cross thread interactions appropriately.

Since this is the first callback you’ll always get, this is a great opportunity to mention that when the initialization call is made is when the server becomes aware of the client's locale. This response, and every response after it, will be sent in the clients locale if at all possible, which means that error messages are not only user friendly but in the users language as well. If you defined game titles and descriptions, etc. for your game in the users language, they will also be used here.

Here’s a simple callback example for game initialization:

Objective-C Code
C++
/** 
* Handle the API having been initialized.
*/
-(void)initializeCompletedWith:(XPGAPIResponse*)response
{
    if (!response.Failed)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"XPG Notice" 
        message:@"Initialized" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"XPG Error" 
        message:response.Message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}
C# Code
C#
///<summary>Handle the API having been initialized.</summary>
///<param name="response" />The server response to the initialization.</param>
private void HandleXPGAPIInstanceInitializeCompleted (XPGAPIResponse<XPGInitGameInfo> response)
{
    if(!response.Failed)
    {
        UIAlertView alert = new UIAlertView ("XPG Notice", "Initialized", null, "OK", null);
        alert.Show ();
    }
    else
    {
        UIAlertView alert = new UIAlertView ("XPG Error", response.Message, null, "OK", null);
        alert.Show ();
    }
}

You’ll notice that not much is going on here. The XPG Live API for iOS handles its state so that your game only needs to be concerned with its own state.

During this initialization the background queue will also spin up to process any score postings, achievement awards, or friend requests which might not have made it to the server before the last shut down.

Announcements for your game are also brought down with initialization, so this callback could be useful for alerts or other user notifications. When this callback is raised, the leaderboards will be initializing their first page of the latest scores already, so there isn’t much for you to do other than handle your game logic.

The Complete Code

Objective-C Code
C++
//
//  RootViewController.h
//  XPGDemoObjC
//

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

@interface RootViewController : UITableViewController <XPGAPIReceiver>
{
}

@end
<code>//
//  RootViewController.m
//  XPGDemoObjC
//

#import "RootViewController.h"

@implementation RootViewController

static NSString* _secretKey = @"DEMOKEY000000001";

- (void)viewDidLoad
{
    [super viewDidLoad];

    [XPGAPI setDelegate:self];
    [XPGAPI initializeWith:_secretKey andCallback:nil];
}

// Standard derived/protocol methods and such removed for brevity

-(void)initializeCompletedWith:(XPGAPIResponse*)response
{
    if (!response.Failed)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"XPG Notice" 
        message:@"Initialized" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"XPG Error" 
        message:response.Message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

@end
C# Code
C#
//
//  RootViewController.cs
//  
//  Author:
//       XPG Inc. <support@xpglive.com>
// 

using System;
using System.Linq;
using System.Drawing;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using XPG;

namespace XPG.Demo.MT
{
    public partial class RootViewController : UITableViewController
    {
        private static string _secretKey = @"DEMOKEY000000001";

        public RootViewController (string nibName, NSBundle bundle) : base (nibName, bundle)
        {
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            XPGAPI.Instance.InitializeCompleted += HandleXPGAPIInstanceInitializeCompleted;
            XPGAPI.Instance.Initialize (_secretKey, null);
        }

        // Standard derived methods and such removed for brevity

        ///<summary>Handle the API having been initialized.</summary>
        ///<param name="response" />The server response to the initialization.</param>
        private void HandleXPGAPIInstanceInitializeCompleted (XPGAPIResponse<XPGInitGameInfo> response)
        {
            if(!response.Failed)
            {
                UIAlertView alert = new UIAlertView ("XPG Notice", "Initialized", null, "OK", null);
                alert.Show ();
            }
            else
            {
                UIAlertView alert = new UIAlertView ("XPG Error", response.Message, null, "OK", null);
                alert.Show ();
            }
        }

        // Data source nested class implementation and such removed for brevity
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.
This is a Organisation (No members)


Comments and Discussions

 
-- There are no messages in this forum --