IPhone

From J2Play

Jump to: navigation, search

Contents

Introduction

This article outlines the steps required to integrate the J2Play iPhone SDK into an iPhone application. For support at any stage of integration please contact J2Play Developer Support.

The iPhone J2Play SDK enables iPhone games to interact with the J2Play platform, providing access to all platform community features, and interaction with social networks and social network friends. Players connecting through this SDK will have a platform presence to social site players listed as playing on iPhone. This is useful for cross promoting the web and mobile versions of a game together. iPhone users of this SDK are all connected to the distributed games network, so users can chat and interact with anyone on the network.

If an accompanying flash game is made with the same gameid, users can play against each other from social web site to iPhone.

Facebook connect & Hi5 connectivity is currently being added to the toolkit so iPhone users with Facebook or Hi5 accounts can login and use their identity to broadcast feeds for viral distribution opportunities across their social sites and add to their overall gamer score and stats of the game network.

Prerequisites

Download the J2Play iPhone SDK

Setup the J2Play iPhone SDK

  • Unzip the downloaded j2play-iphone-sdk package
  • Open the xCode project J2PlaySDK/J2PlaySDK.xcodeproj
  • Build and Go!

The application will output the result of a series of tests to the debug console like so:

[Session started at 2009-04-27 16:43:10 -0400.]
2009-04-27 16:43:13.071 J2PlaySDK[9731:20b] J2Play Test Harness started...
2009-04-27 16:43:13.073 J2PlaySDK[9731:20b] Connecting to J2Play.
2009-04-27 16:43:13.548 J2PlaySDK[9731:20b] My session id: 0c0f522dfbce011ac
2009-04-27 16:43:13.674 J2PlaySDK[9731:20b] Connected to J2Play
2009-04-27 16:43:13.675 J2PlaySDK[9731:20b] Running J2Play communication test examples
2009-04-27 16:43:14.022 J2PlaySDK[9731:20b] ** setScore returns: PASS
MESSAGE_NOTIFY_NOTIFICATION
2009-04-27 16:43:14.105 J2PlaySDK[9731:4003] Received Platform Event
MESSAGE_NOTIFY_NOTIFICATION
2009-04-27 16:43:14.113 J2PlaySDK[9731:4003] Received Badge
2009-04-27 16:43:14.378 J2PlaySDK[9731:20b] ** getScore returns: 2000
2009-04-27 16:43:14.515 J2PlaySDK[9731:20b] ** sendBadgeEvent returns: PASS
MESSAGE_NOTIFY_NOTIFICATION
2009-04-27 16:43:14.531 J2PlaySDK[9731:4003] Received Platform Event
MESSAGE_NOTIFY_NOTIFICATION
2009-04-27 16:43:14.543 J2PlaySDK[9731:4003] Received Badge

Adding the J2Play iPhone SDK to an existing project

This section describes the procedure to add the J2Play iPhone SDK to an existing iPhone application under the debug simulator launch target.

1. In Finder, copy the following folders into your existing project application folder:

J2PlaySDK/j2play
J2PlaySDK/J2PlayLibrary

Copy the following files into your existing project's Classes folder:

J2PlaySDK/Classes/J2Play.mm
J2PlaySDK/Classes/J2Play.h
J2PlaySDK/Classes/Constants.h

2. Open your project

3. Right click on your project in the overview and select Add -> New Group. Name this group J2PlayLibrary

4. Right click on the J2PlayLibrary group and select Add -> Existing files. Select all the header files in the J2PlayLibrary folder you copied to your project. Also right click on the Classes group and select Add -> Existing files. Select the files you added to your Classes folder in step 1.

5. Edit the Constants.h file. Take note of the following lines in this file. These are the settings required to connect to the J2Play platform. Make sure to change the J2PLAY_GAME_ID constant to the game id assigned to you when you registered your game in the J2Play Management Console.

#define DEBUG				1

#define J2PLAY_IP_ADDRESS		"production.j2play.net"
#define J2PLAY_PORT			4501
#define J2PLAY_NETWORK			"j2play"
#define J2PLAY_GAME_ID			"80454"

6. From the Project menu, select Edit Project Settings.

7. Select the Build tab, and scroll down to the Linking section. Double click the Other Linker Flags entry and add the following:

-lJ2PlayLibrary

8. Scroll down further in the Project Settings to the section Search Paths and double click the Library Search Paths entry. Add the following:

j2play/Debug-iphonesimulator

For the iPhone release launch target add the following instead:

j2play/Release-iphoneos

9. Rename your application delegate class and view class (.m extension files) to .mm. The J2Play Library uses mixed Objective C and C++ code, so in order for your application to build, any files which include and use J2Play.h need to have the .mm extension.

10. Build your application.

Integrating Features

Now that the SDK is setup and integrated, here are example code snips of how to use the J2Play Community features from your application. All features have been wrapped up into a single convenient J2Play object.

When communicating with the J2Play platform, spontaneous events will occur which your application will be interested in. To use these events on the iPhone, you will need to subscribe to notifications they will arrive in. In the header file for your main application view add the following:

- (void)subscribeToJ2PlayNotifications;
- (void)eventConnectionBroken:(NSNotification *)notification;
- (void)eventDataMessage:(NSNotification *)notification;
- (void)eventLeave:(NSNotification *)notification;
- (void)eventJoin:(NSNotification *)notification;
- (void)eventGameMessage:(NSNotification *)notification;
- (void)eventChatMessage:(NSNotification *)notification;
- (void)eventChannelProperties:(NSNotification *)notification;
- (void)eventBuddyChatMessage:(NSNotification *)notification;
- (void)eventBuddyStatus:(NSNotification *)notification;
- (void)eventBuddyDetails:(NSNotification *)notification;
- (void)eventBuddyList:(NSNotification *)notification;
- (void)eventLoyalty:(NSNotification *)notification;
- (void)eventBadge:(NSNotification *)notification;
- (void)eventPreference:(NSNotification *)notification;

In the main application view implementation file add the following:

/**
 * Subscribe to all J2Play notifications.
 *
 * @return none
 */
- (void)subscribeToJ2PlayNotifications
{
	// Socket events
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventConnectionBroken:) name:@"EventConnectionBroken" object:nil];
	// Controller events
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventDataMessage:) name:@"EventDataMessage" object:nil];
	// GameChannelManager events
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventJoin:) name:@"EventJoin" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventLeave:) name:@"EventLeave" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventGameMessage:) name:@"EventGameMessage" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventChatMessage:) name:@"EventChatMessage" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventChannelProperties:) name:@"EventChannelProperties" object:nil];
	// BuddyList events
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventBuddyChatMessage:)  name:@"EventBuddyChatMessage" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventBuddyStatus:) name:@"EventBuddyStatus" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventBuddyDetails:) name:@"EventBuddyDetails" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventBuddyList:) name:@"EventBuddyList" object:nil];
	// Remote profile events
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventLoyalty:) name:@"EventLoyalty" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventBadge:) name:@"EventBadge" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:
		@selector(eventPreference:) name:@"EventPreference" object:nil];
}
- (void)eventConnectionBroken:(NSNotification *)notification {
	NSLog(@"Received ConnectionBroken Event");
}
- (void)eventDataMessage:(NSNotification *)notification {
	NSLog(@"Received DataMessage Event");
}
- (void)eventLeave:(NSNotification *)notification {
	NSDictionary *userInfo = [notification userInfo];
	NSLog([NSString stringWithFormat:@"%@ has left.", [j2play nicknameWithSessionID:[userInfo objectForKey:@"playersessionid"]]]);
}
- (void)eventJoin:(NSNotification *)notification {
	NSLog(@"Received Join Event");
}
- (void)eventGameMessage:(NSNotification *)notification {
	NSLog(@"Received Game Message Event");
} 
- (void)eventChatMessage:(NSNotification *)notification {
	NSLog(@"Received Chat message");	
}
- (void)eventChannelProperties:(NSNotification *)notification {
	NSLog(@"Received Channel Properties");
}
- (void)eventBuddyChatMessage:(NSNotification *)notification {
	NSLog(@"Received Buddy Chat");
}
- (void)eventBuddyStatus:(NSNotification *)notification {
	NSLog(@"Received Buddy Status");
}
- (void)eventBuddyDetails:(NSNotification *)notification {
	NSLog(@"Received Buddy Details");
}
- (void)eventBuddyList:(NSNotification *)notification {
	NSLog(@"Received Buddy List Event");
}
- (void)eventLoyalty:(NSNotification *)notification { 
	NSLog(@"Received Platform Event");
}
- (void)eventBadge:(NSNotification *)notification {
	NSLog(@"Received Badge");
}
- (void)eventPreference:(NSNotification *)notification {
	NSLog(@"Received User Preference Event");
}

Initialize the J2Play SDK

The following code provides an example of how to initialize the J2Play SDK:

// Create and Initialize the J2Play object 
j2play = [[J2Play alloc] init];
// Subscribe to event / notifications / callbacks 
// arriving from the J2Play platform
[self subscribeToJ2PlayNotifications];

Login / Registration

The following code provides an example of how to connect / login to the J2Play platform:

// Get device information for unique user identifier
UIDevice *device = [UIDevice currentDevice];
NSString *deviceIdentifier = [[NSString alloc] initWithString:[device uniqueIdentifier]];

// Assign an example screenname (should be provided by the user)
NSString* nickname = [NSString stringWithCString:"Screen name" encoding:NSASCIIStringEncoding];

if (![j2play connect:deviceIdentifier nickname:nickname] ) {
 NSLog(@"Could not connect to J2Play Servers");
}

Getting and Setting Scores

The following code provides an example of how to get and set a simple point score for the current user:

bool result;
// Set a score of 2000 points
long _score = 2000;
result = [j2play setScore:_score];
NSLog(@"** setScore returns: %@\n", (result ? @"PASS" : @"FAIL"));
// Get the score that was just set
_score = [j2play getScore];
NSLog(@"** getScore returns: %d\n", _score);

Getting and Setting Custom Scores

Custom scores or score types can be setup in the J2Play Management Console for each game. A score type represents a score that can be seen in the Leaderboards for that game. For example, if we made a score type of points, where a greater value is a better score, and we want to keep the best one for each use, we can set a score for that type by doing the following:

long _score = 3000;
result = [j2play setScore:@"points" ascending:false numtostore:(int)1 value:_score];
NSLog(@"** setScore with Type returns: %@\n", (result ? @"PASS" : @"FAIL"));

To get the score of the same type do the following:

_score = [j2play getScore:@"points" ascending:false];
NSLog(@"** getScore with Type returns: %d\n", _score);

Badges

Badges and awards are setup by the game developer in the J2Play Management Console. Score based badges will be awarded automatically, and custom badges are awarded when the developer sends a platform event with the id for that badge. Custom badges can only be awarded once per user, executing the following example will invoke the eventBadge notification only one time.

The following code provides an example of how to send a badge event for the current user:

// Custom Badges
int badgeId = 151; // Id from the custom badge event on the admin site
result = [j2play sendBadgeEvent:badgeId];
NSLog(@"** sendBadgeEvent returns: %@\n", (result ? @"PASS" : @"FAIL"));

User Profiles

User profiles are simple key - value pairs of strings that can be get or set for the user. The following code provides an example of how to get and set the user's age in their profile:

// User Preferences
result = [j2play setUserPreference:@"j2play.profile.Age" value:@"21"];
NSLog(@"** setUserPreference returns: %@\n", (result ? @"PASS" : @"FAIL"));
NSString *value = [j2play getUserPreference:@"j2play.profile.Age"];
NSLog(@"** getUserPreference returns: %@\n", value);

Getting and Setting User Profile Picture

User profile pictures are retrieved by their image id which can be obtained upon storing an image in the J2Play Image Service. To store an image in the image service use the following example:

// Save Image into J2Play Image Service with existing ID if exists yet
NSString *imageId = [j2play getUserPreference:@"j2play.profile.imageid"];
NSLog(@"** getUserPreference returns: %@\n", imageId);

NSString *saveImageId = [self uploadImage:imageId];

The following uploadImage method example looks for a userphoto.png file in the iphone user's document directory:

- (NSString *)uploadImage:(NSString *)imageId {
	NSString *result = nil;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);	
	NSString *photoFilename = [[NSString alloc] initWithFormat:@"%@/userphoto.png", [paths objectAtIndex:0]];
	NSLog(photoFilename);
	NSFileManager *fm = [NSFileManager defaultManager];
	BOOL exists = [fm fileExistsAtPath:photoFilename];
	if (exists) {
		NSData *data = [[NSData alloc] initWithContentsOfFile:photoFilename];
		result = [j2play saveImage:data imageId:imageId];
		[data release];
	} else {
		NSLog(@"** could not open image: %@\n", photoFilename);
	}
	[photoFilename release];
	return result;
}

Now that you have stored the image in the J2Play Image Service and obtained an image id, store that image id in the user's profile with the following example:

if (saveImageId) {		
	NSLog(@"** uploadImage returns: %@\n", saveImageId);
	// Save Image ID in profile
	result = [j2play setUserPreference:@"j2play.profile.imageid" value:saveImageId];
	NSLog(@"** setUserPreference returns: %@\n", (result ? @"PASS" : @"FAIL"));
} else {
	NSLog(@"** Skip image upload\n");		
}

To retrieve the image id from the user profile at a later time use the following example:

NSString *imageId = [j2play getUserPreference:@"j2play.profile.imageid"];
NSLog(@"** getUserPreference returns: %@\n", imageId);

To retrieve the actual image back from the J2Play image service use the following:

// Get Image URL for for a 50x50 image
NSString *urlString = [j2play getImageURL:newImageId width:50 height:50];
NSLog(@"** getImageURLForImage returns: %@\n", urlString);
// 
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
image = [[UIImage alloc] initWithData:data]; 
// imageView.image = image; // Use your newly loaded image
[image release];

Using Lobbies

Lobbies are special game channels which have up to 50 players in them at any one time. Lobbies are used for mainly for chat rooms, and to use them you will first have to join a lobby like in the following example:

bool result = [j2play joinThemeLobby];
NSLog(@"** joinThemeLobby returns: %d", result);

This will join a themed lobby like the Movie room or Music room. Theme lobbies are used only for chatting with other players on the platform regardless of which game the other players are in.

Joining a game server lobby will put you in a lobby that only has players which are playing the same game title as you. You can join a game server lobby like in the following example:

bool result = [j2play joinGameServer];
NSLog(@"** joinGameServer returns: %d", result);

Facebook Connect

This section describes how to integrate Facebook Connect and J2Play platform features together. For more details on the Facebook Connect portion make sure to visit http://wiki.developers.facebook.com/index.php/Facebook_Connect_for_iPhone. Included in the J2Play iPhone Toolkit package is an example FBConnect xcode project which demonstrates both Facebook connect and J2Play features together. You will need to be a registered facebook user, to use this example.

  1. Prerequisite: Please visit the J2Play Facebook Developer application at least once before using this example - http://apps.facebook.com/j_devapp/
  2. Open the FBConnect/Connect.xcodeproj file.
  3. Build and Go!
  4. Once the app has launched, click the Facebook Connect and login with your Facebook account.
  5. After successfully logging in, the screen will show a new button at the bottom of the iPhone screen labeled J2Play Tests. Clicking this button will run the same series of platform API calls as the above SDK Test Harness example, however this time as your Facebook identity. Check the debug console for the test output.

Now we will go over the important information regarding the Facebook / J2Play integration.

User Identity

A user identity from a social network (facebook) can also be represented on the J2Play platform. This is achieved by first logging into Facebook, obtaining user identity information, then connecting to J2Play. Here is an example callback from a successful Facebook connect:

// Called when user identity information is received from facebook
- (void)request:(FBRequest*)request didLoad:(id)result {
  NSArray* users = result;
  NSDictionary* user = [users objectAtIndex:0];
  // This user's screen name
  NSString* name = [user objectForKey:@"name"];
  // This user's unique identifier
  NSString* facebookUserId = [user objectForKey:@"uid"];
  NSLog([NSString stringWithFormat:@"Logged into facebook uid %@", facebookUserId]);
  // Connect to J2Play with the id and screenname
  if (![j2play connect:facebookUserId nickname:name]) {
    NSLog(@"Could not connect to J2Play Servers");
  } else {
    NSLog(@"Logged into J2Play Platform successfully");
  }
}

Other platform features

The following platform features will be documented further:

  • Chat
  • Friends List
  • Challenges
  • Multiplay
  • Hi5
  • Social Network Feed Support

** Coming Soon - Sample Multiplayer iPhone game: 4 Degrees by Zapit. This game uses features like iPhone to social site play, live multiplayer, user profiles, chat, advanced scores, and promotion to the app store on social sites.

Personal tools