iOS game center -- frequent CONNECTION INTERRUPTED messages - ios

I am working on an iOS game center game, using GKTurnBasedMatch. Every time an incomplete turn, there is a message in the console like this:
2013-04-26 19:26:45.115 AppName[6439:5a9f] CONNECTION INTERRUPTED
Interestingly, this does not happen when I send a complete turn with
[match endTurnWithNextParticipants: nextParticipants turnTimeout:100000 matchData: data completionHandler:^(NSError* error){
// some block here
}];
but it does happen when I send an incomplete turn with
[match saveCurrentTurnWithMatchData:data completionHandler:^(NSError* error) {
// some block here
}];
Someone else reported a similar problem here: Spurious Game Center player disconnect messages. However, it is difficult to see how the only answer there applies to my situation, as I am creating my matches with GKMatchmakerViewController.

i am having the exact same issue with saveCurrentTurnWithMatchData
infact sometimes i have seen the GameData is not updated with saveCurrentTurnWithMatchData while it returns no error

Related

WatchKit extension crash: "Program ended with exit code: 0"

For people wanting to reply quickly without reading the post: I am not hitting any memory limits. Read the whole post for details.
My WatchKit extension cannot properly function without the user first being "onboarded" through the phone app. Onboarding is where the user must accept the permissions that we require, so it's very crucial.
On my WatchKit extension, I wanted to display a simple warning for users who had not finished onboarding within our phone app yet.
As such, I thought I'd get the status of onboarding from the phone in two ways:
When the user opens the app/the app is activated (I use the willActivate method to detect this)
When the app finishes onboarding it sends a message to the watch of its completion (if the extension is reachable, of course)
Both of these combined would ensure that the status of onboarding is always kept in sync with the watch.
I wrote the first possibility in, utilizing reply handlers to exchange the information. It worked just fine, without any troubles. The warning telling the user to complete disappears, the extension does not crash, and all is well.
I then wrote in the second possibility, of the extension being reachable when the user finishes onboarding (with the phone then directly sending the companion the new status of onboarding). My extension crashes when it receives this message, and I am stuck with this odd error.
Program ended with exit code: 0
My extension does not even get a chance to handle the new onboarding status, the extension just quits and the above error is given to me.
I am not hitting any sort of memory limit. I have read the technical Q&A which describes what a memory usage limit error looks like, and I don't receive any sort of output like that whatsoever. As well, before the extension should receive the message, this is what my memory consumption looks like.
I have monitored the memory consumption of the extension right after finishing onboarding, and I see not a single spike indicating that I've gone over any kind of threshold.
I have tried going line by line over the code which manages the onboarding error, and I cannot find a single reason that it would crash with this error. Especially since the reply handler method of fetching the onboarding status works so reliably.
Here is the code of how I'm sending the message to the watch.
- (void)sendOnboardingStatusToWatch {
if(self.connected){
[self.session sendMessage:#{
LMAppleWatchCommunicationKey: LMAppleWatchCommunicationKeyOnboardingComplete,
LMAppleWatchCommunicationKeyOnboardingComplete: #(LMMusicPlayer.onboardingComplete)
}
replyHandler:nil
errorHandler:^(NSError * _Nonnull error) {
NSLog(#"Error sending onboarding status: %#", error);
}];
}
}
(All LMAppleWatchCommunicationKeys are simply #define'd keys with exactly their key as the string value. ie. #define LMAppleWatchCommunicationKey #"LMAppleWatchCommunicationKey")
Even though it's never called by the extension, here is the exact receiving code of the extension which handles the incoming data, if it helps.
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message {
NSString *key = [message objectForKey:LMAppleWatchCommunicationKey];
if([key isEqualToString:LMAppleWatchCommunicationKeyOnboardingComplete]){
BOOL newOnboardingStatus = [message objectForKey:LMAppleWatchCommunicationKeyOnboardingComplete];
[[NSUserDefaults standardUserDefaults] setBool:newOnboardingStatus
forKey:LMAppleWatchCommunicationKeyOnboardingComplete];
dispatch_async(dispatch_get_main_queue(), ^{
for(id<LMWCompanionBridgeDelegate> delegate in self.delegates){
if([delegate respondsToSelector:#selector(onboardingCompleteStatusChanged:)]){
[delegate onboardingCompleteStatusChanged:newOnboardingStatus];
}
}
});
}
}
Before including this onboarding-related code, my WatchKit extension was tested by over 100 people, without any troubles. I am using the exact same custom error dialogue that I was using before, just with a different string. I cannot for the life of me figure out what is causing this crash, and the ambiguity of it has given me very little to work with.
Any help would be greatly appreciated. Thank you very much for taking your time to read my post.
Edit: I just tried creating a symbolic breakpoint for exit(), which is never hit. If I call exit() myself, it calls the breakpoint, so I know the breakpoint itself is working.

Why does Social.localUser.Authenticate lead to crash when there is no internet connection in Unity app?

With an internet connection
Everything works flawlessly. There is no memory problem leading to crash.
With no internet connection
The app proceeds to the menu screen, where it eventually crashes because it is out of memory.
I have concluded that the problem lies in the following line of code
Social.localUser.Authenticate
When I comment out the above line, the memory problem goes away when there is no internet connection.
Here is my relevant code
void Start ()
{
Social.localUser.Authenticate(ProcessAuthentication);
}
public void ProcessAuthentication(bool success)
{
if(success)
Debug.Log ("Authenticated");
else
Debug.Log ("Failed to authenticate");
}
Leading up to the crash
2016-02-27 15:46:37.131 BrickBall[449:60670] Received memory warning.
WARNING -> applicationDidReceiveMemoryWarning()
2016-02-27 15:46:37.302 BrickBall[449:60670] Received memory warning.
WARNING -> applicationDidReceiveMemoryWarning()
2016-02-27 15:46:37.349 BrickBall[449:60670] Received memory warning.
WARNING -> applicationDidReceiveMemoryWarning()
2016-02-27 15:46:37.437 BrickBall[449:60670] Received memory warning.
WARNING -> applicationDidReceiveMemoryWarning()
Message from debugger: Terminated due to memory issue
Why would that line of code be causing the out of memory crash when there is no internet connect?
My guess is that you'll eventually need to talk to Unity. Game center will use cached credentials when there's no network connectivity to report that it successfully connected to the server and authenticated, even though it didn't. I have a bug open--and an ongoing discussion--with Apple on this. This behavior allows some game types to continue even when there's no network, then sync up later when connection is restored. However, I ran into problems where I assumed I could do things because GC said it was authenticated, but I really couldn't because it really wasn't. :/
This means apps have to handle three cases:
successful authentication with GC
failed authentication with GC
failed authentication, but reported as successful based on cached data
It's possible that Unity doesn't handle the third situation. To confirm or refute this, try the following:
Confirm that Unity does cleanly handle authentication failures
establish connectivity
log out of game center
Break connectivity (airplane mode, etc)
Retry your app
I would expect that success would be false at this point and run cleanly.
If that works as expected, I'd talk to Unity about how they handle Game Center reporting a (cached) success in a disconnected situation.
Edit2:
I had to go back and look at my code to see exactly how I hardened against it. The scenario was: while completely disconnected and/or in airplane mode, Game Center was presenting the "welcome back" message and localPlayer.authenticated was set to YES... BUT, the error code was set and complaining that it couldn't connect.
I opened bug 22232706, "[GKLocalPlayer localPlayer].authenticated always returns true after any authentication handler is set," and which still has an ongoing discussion. Apple confirmed the behavior, but says its intended.
Below is how I hardened my authentication handler to deal with this situation. It won't help you since Unity is handling this for you, but I thought other readers may find this helpful. (The TL;DR version is: always always always check the error code first, before you check .authenticated or before you check if viewController is set)
[localPlayer setAuthenticateHandler:^(UIViewController *loginViewController, NSError *error)
{
//Note: this handler fires once when you call setAuthenticated, and again when the user completes the login screen (if necessary)
//did we get an error? Could be the result of either the initial call, or the result of the login attempt
//Very important: ALWAYS check `error` before checking for a viewController or .authenticated.
if (error)
{
//Here's a fun fact... even if you're in airplane mode and can't communicate to the server,
//when this call back fires with an error code, localPlayer.authenticated is sometimes set to YES despite the total failure. ><
//combos seen so far:
//error.code == -1009 -> authenticated = YES
//error.code == 2 -> authenticated = NO
//error.code ==3 -> authenticated = YES
if ([GKLocalPlayer localPlayer].authenticated == YES)
{
NSLog(#"error.code = %ld but localPlayer.authenticated = %d", (long)error.code, [GKLocalPlayer localPlayer].authenticated);
}
//Do stuff here to disable network play, disable buttons, warn users, etc.
return;
}
//if we received a loginViewContoller, then the user needs to log in.
if (loginViewController)
{
//the user isn't logged in, so show the login screen.
[rootVC2 presentViewController:loginViewController animated:NO completion:^
{
//was the login successful?
if ([GKLocalPlayer localPlayer].authenticated)
{
//enable network play, or refresh matches or whatever you need to do...
}
}];
}
//if there was not loginViewController and no error, then the user is alreay logged in
else
{
//the user is already logged in
//refresh matches, leaderboards, whatever you need to do...
}
}];

Game Center - turn based game issue

I'm developing a turn based game for iOS with a custom interface and i discovered a very odd problem with my matchmaking interface. The following code is used to display a list of active matches, i authenticate the user, then get the list of matches and the last step is to load the match so i can display all the info.
The problem appears when i build the app, go to the matchmaking view controller and leave it alone for 5 minutes; then when i try deleting a match i get an error in loadingMatchWithID:
Error Domain=NSCocoaErrorDomain Code=4097 "The operation couldn’t be completed. (Cocoa error 4097.)
The code works fine every time, deleting, creating matches, refreshing, but if i leave the view controller alone for 5 minutes and then try to delete i get the error. The odd part is the that the localPlayer passes an authentication test, and loads correctly the matches array then stops in loading the match.
One other thing happens, if the error appears and i push the home button and open back the app, everything words again and the matches are loaded correctly.
I think i a problem with the authentication, but where is the mistake ?
UPDATE: The issue appears in iOS7, but in iOS6 it works !
[localPlayer authenticateWithCompletionHandler:^(NSError *error)
{
if (error)return;
[GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error)
{
for (int i = 0; i < matchesArray.count; i++)
{
[GKTurnBasedMatch loadMatchWithID:[[matchesArray objectAtIndex:i]matchID] withCompletionHandler:^(GKTurnBasedMatch *updatedMatch, NSError *error)
{
if (error != nil)
{
NSLog(#"Error: %#",error.description);
}
}];
}
}];
}];
I found what was the issue after many days of searching and testing everything. The problem was with quitting and then removing a match, the removeWithCompletionHandler: was inside the participantQuitInTurnWithOutcome: and somehow these actions would log out the player from game center without any notice, and the odd thing was that all the .isAuthenticated test would succeed.
Probably the most frustrating part was that the code worked for the most part, and worked every time on devices below iOS 7.

Removing a GKTurnBasedMatch which is in an invalid state

I am doing some experimentation to try to learn about GameKit and I made a simple game and an interface which lists my player's matches. I am trying to add the ability to remove games using the removeWithCompletionHandler: method on the match, but I am having trouble removing a GKTurnBasedMatch which seems to have entered an invalid state.
A po of the match in question prints:
$0 = 0x1d590d20 <GKTurnBasedMatch 0x1d590d20 id:858d8257-cc49-4060-b1d8-38c09a929e3c status:Ended message: taken:2013-03-08 18:08:47 +0000 created:2013-03-08 03:24:14 +0000
current:<GKTurnBasedParticipant 0x1d58c020 - id:G:1717956303 (local player) status:Invited outcome:None lastTurn:(null)>
participants:
<GKTurnBasedParticipant 0x1d58bc90 - id:G:1717239488 status:Done outcome:Quit lastTurn:2013-03-08 18:08:47 +0000>
<GKTurnBasedParticipant 0x1d58c020 - id:G:1717956303 (local player) status:Invited outcome:None lastTurn:(null)>
>
Which seems to indicate that the match has been ended. However, one of the participants has the outcome:None, which I am led by the docs to believe is invalid for an ended game. Trying to simply remove the game gives:
The requested operations could not be completed because one or more parameters are invalid.
While trying to set the outcomes and end the game gives:
The requested operation could not be completed because the session is in an invalid state.
I thought perhaps I could not remove the game because the local player is the active participant, but both participantQuitInTurnWithOutcome:... and endTurnWithNextParticipants:... both give the error:
The requested operation could not be completed because the session is in an invalid state.
as well. Am I doing something wrong or did I somehow create an unremovable game?
P.S. I am also unable to remove the games through the Game Center provided interface, where they are listed under the "Game Over" section.
This is how I managed to remove all invalid matches.
I checked the status of the current participant, if it's invited, I called declineInviteWithCompletionHandler, otherwise I called participantQuitInTurnWithOutcome.
In both completion blocks, I then called removeWithCompletionHandler to remove the match.
This generated a few errors but the matches were still removed so my list is clean.
And here is a workaround on how to avoid getting to this state to begin with. This has the added benefit that the invitee never even get a notification if the inviter quits before finishing his/hers first turn.
In playerQuitForMatch, first end the turn and then in the completion handler, immediately quit the match. Like so,
[match endTurnWithNextParticipants:[NSArray arrayWithObject:nextParticipant]
turnTimeout:GKTurnTimeoutDefault
matchData:nil completionHandler:^(NSError *error) {
if (error) {
NSLog(#"%#", error);
}
[match participantQuitOutOfTurnWithOutcome:GKTurnBasedMatchOutcomeQuit
withCompletionHandler:^(NSError *error) {
if (error) {
NSLog(#"%#" ,error);
}
}];
}];
Unfortunately, I've run into the exact same error. To help others understand the problem, in hopes of researching a solution, you can recreate this by inviting a friend to a match, but then quitting the match during the first turn before you ever submit that turn to the invited player. Then, the hosting player removes the match from Game Center. On the invited player's device, they will have a match that looks like the one referenced above, that cannot be deleted. I've tried all types of workaround solutions.
I haven't had any luck yet, but I will update my answer with a solution if I find one. I'm currently trying to ship a Game Center game and so I have to find some way around this. I'll have a conclusion within the next day or two.
UPDATE:
I went over my non-deleteable matches, and they are almost the same as yours except my player with the Invited status also has the match outcome of Won. It seems the key to put the match into an invalid state is to have one player status be Invited instead of Done, but have the match status be Ended. That's the common element between our two cases, and it's an edge case in Apple's bizantine Game Center code. It wouldn't surprise me if they simply screwed up this edge case and expected you to "just know" that you weren't supposed to put the players in that state (undoubtedly if you read their docs closely enough you'll be able to piece this together eventually).
My conclusion is that Apple has an edge case on their hands that goes unnoticed easily because it only can happen if you quit a new match, and only if you invite a friend, two cases you might not test often. Also, if you aren't setting match outcomes improperly I'm guessing it will never happen so they just never caught it.
Since I haven't shipped yet, I'm going to configure my app to detect matches in this state and ignore them. I'm going to report to the console a count of how many matches are in this state, just so I can ensure its not growing past this point. Then, I'm going to analyze my quitting code and make sure that in this edge case that I simply can never put a match into this state again. I think given what we know we've got to be proactive, and just suck up the fact that some matches slipped through.
Hopefully you haven't shipped yet, so the error case matches will be localized to the Game Center Sandbox environment. Actually, the bad matches are just localized to your test user in the Sandbox, so you could just throw away that user and start with a new user once you've corrected your issue. If you implement my above suggestions you should be able to confirm your app is working properly before taking this step.
If anyone can actually find a way to remove these error matches once they exist, please let us know, but I hope my suggestions and identification of the actual cause will be enough to help you proceed with your project.
I found the solution. For invalid matches just use -participantQuitOutOfTurn method and then -removeWithCompletionHandler method. It will be completely removed.
I have a similar situation, if slightly different. I start a match, invite a second sandbox account to play, then the first player quits and deletes the game before the second player can respond. When the second player tries to then quit the game, they get this error:
Error quitting match in turn: Error Domain=GKErrorDomain Code=22 "The requested operation could not be completed because the specified participant is invalid."
UserInfo=0x1f5de800 {
GKServerStatusCode=5097,
NSUnderlyingError=0x1f58b610 "The operation couldn’t be completed.
status = 5097,
Invalid state: turn sent to playerId:1952436619 in slotIndex: 0 for sessionId: 698b074b-fa0b-4505-834f-1b4305b7eecb : expected slot state: Active but found: Inactive",
NSLocalizedDescription=The requested operation could not be completed because the specified participant is invalid.
}
So as far as I can tell, that's happening because the next participant to move already has a status of "Done," which I'm guessing is because they already quit:
<GKTurnBasedMatch 0x1f532b20 id:698b074b-fa0b-4505-834f-1b4305b7eecb status:Open message: taken:2013-03-30 19:53:47 +0000 created:2013-03-30 18:29:09 +0000
current:<GKTurnBasedParticipant 0x1f532b80 - id:G:1952433332 (local player) status:Active outcome:None lastTurn:2013-03-30 19:53:47 +0000>
participants:
<GKTurnBasedParticipant 0x1f532b70 - id:G:1952436619 status:Done outcome:Lost lastTurn:2013-03-30 18:29:10 +0000>
<GKTurnBasedParticipant 0x1f532b80 - id:G:1952433332 (local player) status:Active outcome:None lastTurn:2013-03-30 19:53:47 +0000>
>
Hopefully this will help others diagnose if nothing else. Would love to hear others' insights towards a workaround or solution. If this is a bug on Apple's part, it seems like it might be worth filing a radar.
Apple Technical Developer support confirmed the issue. Submitted bug report. Will keep you posted.

Game Center score reporting problems

I am developing an app that reports a score to Game Center using the code below (as suggested by Apple).
My problem is that even when my iPhone is in Airplane mode, the app does not trigger any score reporting error. It just goes to the "Submission ok" section of the code.
Any idea why?
Thank you!
GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:category] autorelease];
scoreReporter.value = score;
[scoreReporter reportScoreWithCompletionHandler:^(NSError *error) {
if (error != nil)
{
// handle the reporting error
NSLog(#"Error Descr %#",error.localizedDescription);
NSLog(#"Error Code %#",error.code);
NSLog(#"Error Domain %#",error.domain);
}
else {
NSLog(#"Submission ok");
}
}];
Starting with iOS 5.0, any network errors arising out of reportScoreWithCompletionHandler are handled internally by GameKit. This means that developers no longer have to worry about resubmitting scores pending due to network failures. If you're building with iOS 5.0 and later, the completion handler of reportScoreWithCompletionHandler will not receive any network-related errors.
I would suggest using Apple's reachability flags to detect an active connection yourself. If a connection isn't available, store your Game Center requests for future submission and submit them when network becomes available again. More on reachability can be found here

Resources