Submitting Score to Game Center - iphone

I'm using a Game Center leaderboard, which works fine and shows scores as it should do. The only problem is when I simulate a network failure (well, put the phone into airplane mode) it still returns a null error when posting a score. The posting code is -
[scoreReporter reportScoreWithCompletionHandler: ^(NSError *error)
{
[self callDelegateOnMainThread: #selector(scoreReported:) withArg: NULL error: error];
}];
which you would expect to return "unsuccessful" in this case. I've no idea what's going on! Any help appreciated, thanks.

Well, I've sort of worked around it - I've used Apple's Reachability code just to check if the phone can connect, then I do the Game Center stuff. It's weird, but the Game Center doesn't show any error if there's no network when it submits a score, but it does if there is a network & it can't connect to its servers. Unless I'm doing something totally wrong, but it's more-or-less a cut & paste of their own example code.

Related

Game Center lag with Memory Warning

I have almost finished an iPhone game made with cocos2d 2.0, and the last thing I did was add Game Center. I am using an iPod 4 for testing. I followed this tutorial: http://www.raywenderlich.com/23189/whats-new-with-game-center-in-ios-6
The problem is that when I try to submit a score to Game Center, the game starts to stutter / lag like crazy for 5-10 seconds. This happens when I call the following:
[gkScore reportScoreWithCompletionHandler:
^(NSError* error) {
[self setLastError:error];
BOOL success = (error == nil);
if ([_delegate
respondsToSelector:
#selector(onScoresSubmitted:)]) {
[_delegate onScoresSubmitted:success];
}
}];
The score is sent successfully without errors, but the game lags a lot when sending and memory warnings appear in the console. This problem seems to be related to a "CONNECTION INTERRUPTED" message that appears in the console beforehand, that seems to occur when the game's memory usage is around 60MB. The game doesn't lag when I try submitting a score earlier, before that message appears.
I searched around and found it strange that nobody else seems to complain about this, is this normal? Any help is much appreciated, thanks!

iPhone Simulator 6.0 not able to connect to gamecenter in sandbox mode

I'm trying to implement a gamecenter aware app targeted to iOS 6. To give some info on the environment I'm working on mac os 10.7.5 with XCode version is 4.5.2 and xcode is running iphone and ipad simulator version 6.0. The problem is I cannot connect to gamecenter in sandbox mode neither through ipad or iphone simulator, but the same code works as desired while testing in my iphone.
I followed the gamecenter programming guide in apple's developer library and I got this atm it is called from applicationDidFInishLaunching in appdelegate:
- (void)authenticateLocalUser:(UIViewController *)currentViewController
{
if (!gameCenterAvailable) return;
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){
if (viewController != nil)
{
[currentViewController presentViewController:viewController animated:YES completion:nil];
}
else if (localPlayer.isAuthenticated)
{
NSLog(#"Player authenticated");
}
else
{
NSLog(#"Player not authenticated");
}
NSLog(#"Error: %#",error);
};
}
It outputs:
Error: Error Domain=GKErrorDomain Code=2 "The requested operation has been cancelled."
UserInfo=0x8690510 {NSLocalizedDescription=The requested operation has been cancelled.}
GKSConnSettings: set server: {
"gk-cdx" = "17.173.254.218:4398";
"gk-commnat-cohort" = "17.173.254.220:16386";
"gk-commnat-main0" = "17.173.254.219:16384";
"gk-commnat-main1" = "17.173.254.219:16385";
}
I already tried hosts file fix though my OS is not 10.8.2 but it didn't help. https://devforums.apple.com/thread/168811?tstart=0
Any idea what can be the possible cause?
Edit: Well, it turns out the output part starting with GKSConnSettings does not indicate any problems, that's the regular output while connecting to game center as I understood from what I read over internet. I printed the actual error message (GKErrorDomain = 2 ...) inside the authentication block.
I got the inspiration from : https://stackoverflow.com/a/8115807/837244, and decided to log in to game center account with a different piece of code. So in viewdidload I normally called:
[[GCHelper sharedInstance] authenticateLocalUser:self];
Now I commented that out, accessed game center through below URL scheme, logged in to my account and after that logged out.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"gamecenter:"]];
And lastly reverted back by commenting out URL code and using the original code. Now it works fine, I guess the problem was that a game center account was already hooked up in simulator and it denied every login request bc of that. Hope apple goes clearer with error messages, it took a month to fix such a simple issue, may this help to others.
I know this question references specific Xcode and iOS simulation versions, but if your simulator is already logged in one account, and you don't mind losing whatever data you've got on the simulator (chances are small, but you never know), you can simply reset the settings and data on it.
Go to:
Simulator -> Reset Content and Settings...
...and confirm the action when prompted.
This is certainly true for Xcode7.x running an iOS 9.x simulator, someone else might be able to verify whether it's true for earlier versions (especially as I've unearthed quite an old question and answer).
Animal451
Necrothreadomancy: +1

GKLocalPlayer getting profile pictures

I'm working with Game Center Kit, how can I get the image of game center user(my friend, or anyone else) thnx
There is an asynchronous method to load either a small or normal sized player image (only available in iOS5):
- (void)loadPhotoForSize:(GKPhotoSize)size
withCompletionHandler:(void (^)(UIImage *photo, NSError *error))completionHandler

iOS Development: How do I auto match players in Game Center?

I have a "Play Now" button in my app that allows players to be auto-matched with other random players. Maybe I'm missing this somewhere in the docs, but how do I write the code to auto match players?
The Game Center sandbox server has been messed up the last few days, so I'm having a hard time trying different things since I have to guess because the Game Kit docs aren't exactly clear on how to do this. Currently, I have code setup (but untested) to create a match with a friend...
NSArray *playerList = [NSArray arrayWithObject:pid];
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 2;
request.maxPlayers = 4;
request.playersToInvite = playerList;
[[self waitingIndicator] startAnimating];
[[GKMatchmaker sharedMatchmaker] findMatchForRequest:request withCompletionHandler:^(GKMatch *match, NSError *error) {
if (error)
{
//handle error
}
else if (match != nil)
{
self.myMatch = match;
//start match code
}
}];
But how do I auto match two random people looking for a game? My guess, since the docs don't say it, or I'm missing it, is that in order to create an auto match, I simply set the playersToInvite property of the match object to nil? If not, how do I create an auto match?
One other question, while we're on the topic, the Game Kit docs site a few common matchmaking scenarios, one of them being...
A player can also create a network
match using the Game Center
application. When they invite a friend
into a multiplayer game, your
application is launched on both
devices, and each copy of your
application receives an invitation to
join the game.
But I can't figure out how to do this in the Game Center app for testing purposes. How does a user create a network match using the Game Center app? I don't see any buttons for that anywhere in the Game Center app.
Thanks in advance for your wisdom!
Ok, now that the sandbox Game Center server is back up, I was able to confirm that auto-matching works by setting the playersToInvite property to nil, or not setting it all.

GameCenter login alert

In a game I am developing using GameCenter, I want to handle the following scenario:
the user starts up the game. He is shown the system alert that prompts him to log on GameCenter. He ignores it for now.
after a while, the user wants to log in to GameCenter and clicks on(for instance) the Leaderboards menu item. He choses cancel instead of Log in, for now.
the process repeats several times. Eventually the user DOES want to log in to GameCenter. He clicks the Leaderboard menu item one more time.
In my tests, I have found that the alert popup raised by the call to "authenticateWithCompletionHandler" (as invoked by Apple's sample GameCenterManager) which suggests to log in to GameCenter only appears a limited number of times(4 or 5). The last time it appears, it says "Game Center Disabled, sign in with the Game Center application to enable"Afterwards". Afterwards, calling authenticateWithCompletionHandler no longer does anything visible -no prompt at all.
Playing FruitNinja I tried to replicate this. However, in their case, the popup saying "Game Center Disabled" does appear every time I click on a GameCenter item(Achievements, for instance).
What I'd like to do is to duplicate the functionality: that is, if you are not logged in to GameCenter, to have the standard game center alert appear all the times you click on the Leaderboard menu item.
Is there a way to learn whether the standard 'log in to game center' alert has appeared, or to force it to appear at all times(and not just the first couple of tries)?
Here's an is an idea to workaround this issue:
No matter if a "GC authenticateWithCompletionHandler"-Request is cancelled
by the user tapping "Cancel" in the dialog
or due to the fact that
GC is disabled on the device (which happens after the user has cancelled the alert-dialog exactly 3 times (in iOS 5 at least))
you will always receive an NSError with code 2 saying "The requested operation has been cancelled.".
The only differentiator that i could find is the time passed between the authenticateWithCompletionHandler-Request and the the execution of the completion-Handler.
So when sending the request i am saving the time:
requestTime = [NSDate date];
and in my completion handler i measure the time lapsed:
NSDate* now = [NSDate date];
CFTimeInterval elapsedTimeSinceAuthenticationRequest = [now timeIntervalSinceDate:requestTime];
NSLog(#"time Elapsed: %f", elapsedTimeSinceAuthenticationRequest);
If the user cancelled the request, the time passed will be significantly longer compared to the time passed if GC cancelled the operation. In my tests, it took a user at least one second to cancel the dialog, whereas a GC-cancelled request took less than 0.1 seconds (on my iPhone 4)
Of course, these values may vary depending on the device the code runs on and on what else the processor is busy with at the moment. One pitfall i already examined is the application launch: If you are sending the authenticationRequest during applicationDidFinishLaunching as suggested by Apple, it took much longer for GC to cancel the request in my case, because the device is busy loading views and whatever is necessary to launch the app.
So let me know if you tried this solution and if it worked for you, as will i once i have done further testing...
The behavior is something to the effect of, after N unsuccessful attempts - disable GameCenter for the app. Restarting the app or going to login in gamecenter itself will get it back online.
I forget which doc I read this in, but there is an Apple doc out there that explains this behavior.
I couldn't find a good answer for this either, so I decided to just replicate the message once the I start getting the cancel error. This is still in development but it basically changes the button callback to display the error alert rather than display the leader-board.
Just a note, not sure if this will be approved or not since I am replicating an Apple error message.
-(void) gcLogin: (id) sender {
[[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) {
if(error) {
if([[error domain] isEqualToString:GKErrorDomain] && [error code] == GKErrorCancelled) {
[ResourceManager showAlertWithTitle:#"GameCenter Disabled" message:#"Sign in with Game Center application to enable"];
mGameCenterCancelled = YES;
}
NSLog(#"%#", [error description]);
} else {
[self updateMenu];
mGameCenterCancelled = NO;
}
}];
}
I am playing around with Game Center myself right now I have seen the very same behavior. There is nothing in the documentation saying anything about the dialog only showing up the first couple of times.
In my case I would like a way to tell beforehand if the user is already logged into Game Center, so that I can behave appropriately. But now I can not know this before the dialog is shown to the user.
Since we are running in the sandbox during development this behavior might of course be something that behaves differently during production but this is not an easy thing to find out.
May be the link will helpful (First three paragraphs):
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/GameKit_Guide/Users/Users.html#//apple_ref/doc/uid/TP40008304-CH8-SW9
The main point is in a rectangle "Important".
I'm facing the same issue. Though I couldn't find a way to enforce poping up the same dialog for logging into Game Center, I did find a way to implement a warning message saying 'gamecenter is disabled' when user clicks on a leaderboard icon:
if([GKLocalPlayer localPlayer].authenticated == NO)
{
// Prompt a warning message alert saying game center is disabled
}
else
{
// Proceed with opening leaderboard
}
Hope this helps!
It appear that iOS will disable Game Center completely and prevent it from prompting after the user chooses to Disable Game Center (the option would appear on your fifth 5th Game Center cancel sign in).
To restore the device to the original state where the login prompt will appear again. Simply sign in using the Game Center app using a normal working Game Center account (non Tester). Once you are in, Sign Out. It should start prompting you again on within your app.