i establish a connection between two iOS devices with GameKit and GKMatch for a synchronous game. When one player enter the background the connection will disconnect. How can I avoid this behavior? Is it possible to keep the connection via GKMatch alive while one user did suspend the app to the background?
Share
According to Apple’s documentation:
Source: Game Center Programming Guide, pg. 39.
Unless your App employs VOIP or special circumstances apply, you shouldn’t really be keeping a network connection open in the background. (If you are interested though, check out this SO question for a hacker-ish way of going about that).
As your player authentication is invalidated on entering the background, another device (if it does manage to receive network data from the background App) will not (reliably) know which GKPlayer sent the information.
So while Apple don’t come out and say it explicitly, all Game Center features should normally be cancelled when the Application enters the background, and resumed once the player is re-authenticated upon relaunch.
As a side note, when an App withdraws to the background it is (usually, depending on background tasks) deemed “eligible for suspension”. This is one reason there are such restrictions on multitasking execution – your App could be killed at any moment to free memory and you don’t really want a heavy duty data transfer going on when that happens!
See TN227 if you’d like to know more about networking and multitasking.
EDIT: An alternate method:
While it is not possible to keep a GKMatch alive while an App is running in the background, an alternative way to emulate this behaviour would be to save game state to your own server. Ask the user to interact with some UI (press a button maybe) before she/he leaves the game, which saves the current game state to your own server and notifies the other player that you are about to leave the game. Upon relaunch, query your server to see if you have any saved games, and if so, load the game state and send a notification to the other player. This doesn’t strictly maintain the same game, but is one way of approximating the behaviour you’re after.