Game Center Invitation - iphone

I am using Game Kit and I want to submit a score on Game Center. I did that but now I want to invite friends. How do I invite my friends and how do I see my friend's score? This code is for show leaderboard:
- (IBAction) showLeaderboard
{
GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
if (leaderboardController != NULL)
{
leaderboardController.category = self.currentLeaderBoard;
leaderboardController.timeScope = GKLeaderboardTimeScopeWeek;
leaderboardController.leaderboardDelegate = self;
[self presentModalViewController: leaderboardController animated: YES];
}
}

The general functions needed for friend interaction in Game Center can be found in Working with Players in Game Center.
There is even a section on inviting friends under Allowing the Local Player to Invite Other Players to Be Friends:
- (void) inviteFriends: (NSArray*) identifiers
{
GKFriendRequestComposeViewController *friendRequestViewController = [[GKFriendRequestComposeViewController alloc] init];
friendRequestViewController.composeViewDelegate = self;
if (identifiers)
{
[friendRequestViewController addRecipientsWithPlayerIDs: identifiers];
}
[self presentViewController: friendRequestViewController animated: YES completion:nil];
[friendRequestViewController release];
}

Related

Game Center Leaderboards with cocos2d Cause Unresponsive App

OK, so I'm trying to show Apple Game Center Leaderboards called from within my cocos2d game.
I've had some trouble doing so.
I did eventually stumble upon this and I implemented the following in one of my CCScene classes (I slightly modified the original code to prevent a compiler warning).
- (void)showLeaderboardForCategory:(NSString *)category
{
// Create leaderboard view with default Game Center style
leaderboardController = [[GKLeaderboardViewController alloc] init];
// If view controller was successfully created...
if (leaderboardController != nil)
{
// Leaderboard config
leaderboardController.leaderboardDelegate = self; // leaderboardController will send messages to this object
leaderboardController.category = category;
leaderboardController.timeScope = GKLeaderboardTimeScopeAllTime;
// Create an additional UIViewController to attach the GKLeaderboardViewController to
vc = [[UIViewController alloc] init];
// Add the temporary UIViewController to the main view
[[CCDirector sharedDirector].view.window addSubview:vc.view];
// Tell UIViewController to present the leaderboard
[vc presentModalViewController:leaderboardController animated:YES];
}
}
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
[vc dismissViewControllerAnimated:YES completion:nil];
}
And, it works! At least when I call it, it does display the Leaderboard properly.
The only problem is, when I tap "Done" on the Leaderboard and the modal view dismisses, my CCScene no longer responds to tap events.
What do I need to do to regain responsiveness?
Refer sample plain cocos2d project:
-(void)showLeaderboard
{
GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init];
leaderboardViewController.leaderboardDelegate = self;
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] presentModalViewController:leaderboardViewController animated:YES];
[leaderboardViewController release];
}
Delegate Function:
-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] dismissModalViewControllerAnimated:YES];
}

How to accept an invitation in Game Center

I'm trying to implement invitations with Game Center and there's one thing that i don't understand. Ok, i've sent an invitation from one device to another. Then i have an UIAlertView on receiver which asks me i would like to accept or decline the invitation. when i accept it it is handled like this:
[GKMatchmaker sharedMatchmaker].inviteHandler = ^(GKInvite *acceptedInvite, NSArray *playersToInvite)
{
// Insert application-specific code here to clean up any games in progress.
if (acceptedInvite)
{
GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithInvite:acceptedInvite] autorelease];
mmvc.matchmakerDelegate = self;
[presentingViewController presentModalViewController:mmvc animated:YES];
}
else if (playersToInvite)
{
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 2;
request.maxPlayers = 4;
request.playersToInvite = playersToInvite;
GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease];
mmvc.matchmakerDelegate = self;
[presentingViewController presentModalViewController:mmvc animated:YES];
}
};
Well, that's great, but what next? the sender device is obviously waiting for some standard type of response, cause it also shows an alert telling me that there's some invitations not answered yet if i tap "Play now".
So how do i accept an invitation? What kind of data (and how) should i send back? And what exactly should i do on the receiver's side? Should game start instantly after tapping "Accept" or i should dismiss the AlertView first and then tap "Play now"?
Ray Wenderlich's tutorial says that i should choose second way but when dismiss the alert and tap "Play now" it turns out the sender device is still waiting for response and is not aware that i have already accepted the invitation. if i tap "Play now" at this moment then, as i said above, it shows an alert which says that the application is waiting for the response. So if you've ever done that then please explain me what should i do. Thanks!
I register for invites as soon as the game is loaded and call the
delegate when an invite is received
So inviteReceived calls the match maker for dismissing the game
center controller and creating the match
And finally, when the match is being found, the method
connectionStatusChanged takes care of presenting all the game's
views and players and stuff
Here is the code:
I register for invites as soon as the game is loaded and call the delegate when an invite is received:
- (void)registerInvites {
[GKMatchmaker sharedMatchmaker].inviteHandler = ^(GKInvite *acceptedInvite, NSArray *playersToInvite) {
self.pendingInvite = acceptedInvite;
self.pendingPlayersToInvite = playersToInvite;
[delegate inviteReceived];
};
}
So inviteReceived calls the match maker for dismissing the game center controller and creating the match:
- (void)inviteReceived {
[[GCMultiplayerHelper sharedInstance] findMatchWithMinPlayers:2 maxPlayers:2 viewController:(UIViewController*)[self.superview nextResponder] delegate:self];
}
- (void)findMatchWithMinPlayers:(int)minPlayers maxPlayers:(int)maxPlayers viewController:(UIViewController *)viewController delegate:(id<GCMultiplayerHelperDelegate>)theDelegate {
if (!gameCenterAvailable) return;
matchStarted = NO;
self.match = nil;
self.presentingViewController = viewController;
delegate = theDelegate;
[presentingViewController dismissModalViewControllerAnimated:YES];
GKMatchmakerViewController *mmvc;
if (pendingInvite != nil) {
mmvc = [[[GKMatchmakerViewController alloc] initWithInvite:pendingInvite] autorelease];
} else {
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = minPlayers;
request.maxPlayers = maxPlayers;
request.playersToInvite = pendingPlayersToInvite;
mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease];
}
mmvc.matchmakerDelegate = self;
[presentingViewController presentModalViewController:mmvc animated:YES];
self.pendingInvite = nil;
self.pendingPlayersToInvite = nil;
}
And finally, when the match is been found, the method connectionStatusChanged takes care of presenting all the game's views, players and starting the match:
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)theMatch
{
self.match = theMatch;
match.delegate = self;
if (!matchStarted && match.expectedPlayerCount == 0) {
NSLog(#"Ready to start match! - didFindMatch");
[presentingViewController dismissModalViewControllerAnimated:YES];
[self.delegate connectionStatusChanged:CONNECTIONSUCCESS];
}
}
I've successfully implemented an online game center match following Ray's tutorials. The answer to you question is: You don't have to send anything to the inviting device. When you call the line:GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease];, the matchMakerVController handles the connection . However, you should write an invitation handler ASAP, preferably in the authentication changed method. See mine:
-(void) authenticationChanged {
if ([GKLocalPlayer localPlayer].isAuthenticated && !userAuthenticated) {
NSLog(#"Authentication changed: player authenticated.");
userAuthenticated = TRUE;
[self sendUnsentScores];
[GKMatchmaker sharedMatchmaker].inviteHandler = ^(GKInvite *acceptedInvite, NSArray *playersToInvite){
NSLog(#"Invite");
if([AppDelegate mainMenuController].presentedViewController!=nil) {
[[AppDelegate mainMenuController] dismissViewControllerAnimated:NO completion:^{
}];
} // if we're not on the main menu, or another game is going on.
// this would be easier to do if you were using a navigation controller
// where you'd just push the multiplayer menu etc.
self.pendingInvite = acceptedInvite;
self.pendingPlayersToInvite = playersToInvite;
[[AppDelegate mainMenuController] presentViewController:[AppDelegate mainMenuController].multiGameMenu animated:NO completion:^{ // push the multiplayer menu
[[AppDelegate mainMenuController].multiGameMenu duel:nil];
}];
};
}
and here is the duel method if you're interested. Very messy code but deal with it :)
- (IBAction)duel:(id)sender {
NSLog(#"duel");
if (presentingMenu.multiGameController==nil || presentingMenu.multiGame.gameInProgress==NO) {
presentingMenu.multiGame=nil;
presentingMenu.multiGameController=nil;
MultiViewController *mvc = [[MultiViewController alloc] init]; //create game VC
presentingMenu.multiGameController = mvc; //presenting menu is just the main menu VC
// it holds this menu, and the game
// objects.
}
if (presentingMenu.multiGame == nil) {
presentingMenu.multiGame = [[MultiGame alloc] // similarly create the game object
initWithViewController:presentingMenu.multiGameController];
//they both have pointers to each other (A loose, bad MVC).
presentingMenu.multiGameController.game = presentingMenu.multiGame;
[presentingMenu.multiGame startGame];
}
if (presentingMenu.multiGameController.gameState==0) { //new game
presentingMenu.multiGameController.game = presentingMenu.multiGame;
[[GCHelper sharedInstance] findMatchWithMinPlayers:2 maxPlayers:2 viewController:self delegate:presentingMenu.multiGame]; // the GC magic happens here - it know about the invite.
} else {
[self presentViewController:presentingMenu.multiGameController animated:YES completion:^{
}];
}
}
inviteHandler = ^(GKInvite *acceptedInvite, NSArray *playersToInvite) is deprecated now. See the new way to register for invite notifications.
GKMatchMaker invite handler deprecated

Dismissing GameKit modal view

I am trying to integrate Apple's game center into my application. I can successfully post scores to the leader board, and show the leader board, but the problem comes when I try to dismiss the leader board modal view. I've followed apple's code direction from the Game Kit Programming Guide ([url]http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/GameKit_Guide/LeaderBoards/LeaderBoards.html[/url]).
My code is as follows for Game Center:
-(BOOL)isGameCenterAvailable{
// Check for presence of GKLocalPlayer class.
BOOL localPlayerClassAvailable = (NSClassFromString(#"GKLocalPlayer")) != nil;
// The device must be running iOS 4.1 or later.
NSString *reqSysVer = #"4.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);
return (localPlayerClassAvailable && osVersionSupported);
}
- (void) authenticateLocalPlayer
{
if([self isGameCenterAvailable]){
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
[localPlayer authenticateWithCompletionHandler:^(NSError *error) {
if (localPlayer.isAuthenticated)
{
// Perform additional tasks for the authenticated player.
}
}];
}
}
- (void) reportScore: (int64_t) score forCategory: (NSString*) category
{
GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:category] autorelease];
scoreReporter.value = score;
[scoreReporter reportScoreWithCompletionHandler:^(NSError *error) {
if (error != nil)
{
// handle the reporting error
}
}];
}
- (void) showLeaderboard
{
GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
if (leaderboardController != nil)
{
leaderboardController.leaderboardDelegate = self;
[self presentModalViewController: leaderboardController animated: YES];
}
//[leaderboardController release];
}
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
if([self modalViewController] != nil){
[self dismissModalViewControllerAnimated:YES];
}
}
-(IBAction)show{
[self showLeaderboard];
}
-(IBAction)submit{
[self reportScore:9 forCategory:kLeaderboardID];
}
Xcode tells me the problem line is [self dismissModalViewControllerAnimated:YES]; it says I'm getting bad access, which I know means I'm trying to access a bad pointer, but I don't see why anything wouldn't be invalid. Self reports that it has a modalviewcontroller. I've tried all sorts of variants, and I'm completely baffled as to why it is giving me errors.
Any help or suggestions would be greatly appreciated.
Thanks in advance!
I just had a very similar issue on my App. I discovered that it was not related to the ModalViewController itself but the view controller displaying it.
If you profile the app using the zombies option in the Profiler, you will be able to see that something is being released that should not be (Most likely a UIImage or UIView). You should be able to track down the function where the zombied object was allocated to find the real object causing the trouble.
I am supposing that the reason the error shows when the ModalViewController is dissmissed is that various view elements are called to redraw or refresh after the dialog goes away and then something gets accessed that was released when it shouldn't have been.
Hope this helps.

lost control in LeaderBoard - GameCenter

I want to add Game center for my project but now I get some stuck and can't find any solution for my problem by Google :(
When I call method showleaderboard in my project, leaderboard appear and success to load my score in gamecenter but it don't receive touch (this screen look like freeze).
This is my code:
-(void) ShowLeaderBoardCategory:(NSString *)my_category
{
GKLeaderboardViewController * leaderboardController = [[GKLeaderboardViewController alloc] init];
if(leaderboardController != nil)
{
leaderboardController.category = my_category;
leaderboardController.leaderboardDelegate = mySubView;
[mySubView presentModalViewController: leaderboardController animated: YES];
[glView addSubview:mySubView.view];
}
[leaderboardController release];
}
-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
[mySubView dismissModalViewControllerAnimated:YES];
[mySubView release];
[viewController.view removeFromSuperview];
[viewController release];
}
mySubView is interface I define:
#interface MyUIView : UIViewController<GKLeaderboardViewControllerDelegate>
......
and used it:
MyUIView *mySubView;
Please, tell me what wrong in my code? :((
What reason can there be to stop receiving cocos2d events?
Thanks for reading and hope your hint.
[viewController.view.superview removeFromSuperview];
worked for me.
The problem is in your removal method: where viewController refers to the leaderboard:
[mySubView dismissModalViewControllerAnimated:YES]; //this removes the modally presnted leaderboard.
[mySubView removeFromSuperview]; //this should show up the glView

how to get around lack of 'add' button in ABPeoplePickerNavigationController?

My app needs to associate instances of a custom class with contact records in the iPhone's AddressBook. Everything's all well and good when I present the ABPeoplePickerNavigationController and allow the user to pick an existing contact. Problem is there's no obvious way to allow a user to easily ADD a contact record if the one they're looking for doesn't already exist in their AddressBook.
How are people getting from ABPeoplePickerNavigationController to ABNewPersonViewController in a way that's easy & intuitive for the user?
You can create a UIBarButton and add it to the UINavigationBar of the ABPeoplePickerNavigationController like so.
peoplePicker.topViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(addPerson:)];
-(IBAction)addPerson:(id)sender{
ABNewPersonViewController *view = [[ABNewPersonViewController alloc] init];
view.newPersonViewDelegate = self;
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:view];
[self.picker presentModalViewController:nc animated:YES];
}
The issue that i came up against was that the ABPeoplePickerNavigationController has a cancel button placed in the rightBarButtonItem slot and I had to update the navigation bar on the
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
I have documented the entire process on my blog with a worked example that should allow you to create a contacts style application similar to that on the iPhone. Hope this helps.
I found Scott Sherwood's approach along with the demo he posted on his site to be very helpful. As one of the commenters on his blog mentioned though, there is a problem with the Cancel button in Edit mode.
I just proposed a fix to Scott's demo, along with a different approach for the Person View Controller at:
http://finalize.com/2013/05/12/using-and-customizing-the-address-book-ui/
My suggestion for the Person View Controller was to put it up manually in the protocol method peoplePickerNavigationController:shouldContinueAfterSelectingPerson: for the ABPeoplePickerNavigationControllerDelegate.
// Displays the information of a selected person
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABPersonViewController *view = [[ABPersonViewController alloc] init];
view.personViewDelegate = self;
view.displayedPerson = person; // Assume person is already defined.
view.allowsEditing = YES;
view.allowsActions = YES;
[peoplePicker pushViewController:view animated:YES];
return NO;
}
The only issue here is that the People Picker table view of names is not refreshed automatically after an edit. This can be fixed with the use of an Address Book callback. I show how this can be done in the GitHub project I posted at:
https://github.com/scottcarter/AddressBookPeoplePicker.git
it appears that it is not possible to add a new contact directly from the ABPeoplePickerNavigationController. Therefore, when the user clicks an add button, I am presenting an UIActionSheet with two buttons:
- (void) addContact{
contactMenu = [[UIActionSheet alloc]
initWithTitle: nil
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle: nil
otherButtonTitles:#"Select a contact", #"Add a new contact", NULL];
[contactMenu showInView:self.view];
}
Here is the associated delegate method:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0){
// select an existing contact
ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
peoplePicker.peoplePickerDelegate = self;
[self presentModalViewController:peoplePicker animated:YES];
}
if(buttonIndex == 1){
// add a new contact
ABNewPersonViewController *newPersonViewController = [[ABNewPersonViewController alloc] init];
newPersonViewController.newPersonViewDelegate = self;
UINavigationController *personNavController = [[UINavigationController alloc] initWithRootViewController:newPersonViewController];
[self presentModalViewController:personNavController animated:YES];
[personNavController release];
[newPersonViewController release];
}
if(buttonIndex == 2){
// cancel the operation
[actionSheet dismissWithClickedButtonIndex:2 animated:YES];
}
}