The following code is called once upon applicationDidFinishLaunching:; however, it runs each time my app re-enters the foreground again.
[localPlayer authenticateWithCompletionHandler:^(NSError *error) {
if (localPlayer.isAuthenticated)
{
// Some implementation
}
}];
This makes sense, according to the Game Kit Programming Guide:
... it also retains your completion handler for later use. Each time your application is moved from the background to the foreground, Game Kit automatically authenticates the local player again on your behalf and calls your completion handler to provide updated information about the state of the authenticated player.
Is there any way to delay this authentication until Game Center is actually needed? The reason I ask is that I would like to avoid showing the "Welcome back, userX!" banner each and every time the app is brought to the foreground.
No, you can't, at least not with public APIs.
Related
I'm implementing GADRewardedInterstitialAd into a game.
https://developers.google.com/admob/ios/api/reference/Classes/GADRewardedInterstitialAd
I'm using presentFromRootViewController:userDidEarnRewardHandler to react to the user finishing the ad.
Now I'd also like to know how to react to the user cancelling the ad.
If I continue directly after calling presentFromRootViewController, the callback handler will not have been called yet, because the systems works asynchonous, as is to be expected. So any game animations (e.g. screen fade, dialog close) will have to be stalled.
If I rely only on the handler, I won't get a callback when the ad was cancelled.
My solution would be to build in a timer that waits 30+1s to give the handler a chance to get called (hopefully on the next main thread dispatch cycle), and then react to it not being called yet (assuming a cancellation by the user).
I really hate that plan.
It's not deterministic.
It doesn't use callbacks/delegates/handlers (which are great exactly for this kind of thing)
I have to write the timer code and keep a boolean flag somewhere... it's messy.
It adds an arbitrary delay to the user experience (30+1s) when they close the ad!!
Am I thinking the wrong way about this or is this just the way Google has made it and I'll have to live with it?
Edit: please note that I'm talking about the new GADRewardedInterstitialAd API, not GADRewardedAd.
I've figured it out; it works by setting GADFullScreenContentDelegate fullScreenContentDelegate and implementing adDidDismissFullScreenContent.
In there you can check if this particular instance of GADRewardedInterstitialAd did not get a reward yet (as notified by userDidEarnRewardHandler...)
This all hinges on the assertion that adDidDismissFullScreenContent gets called AFTER the userDidEarnRewardHandler, else I will already have assumed there was no reward. Let's hope that is always the case.
https://developers.google.com/ad-manager/mobile-ads-sdk/ios/api/reference/Protocols/GADFullScreenContentDelegate
I am trying to run some code during the applicationWillResignActive when the user opens the task switcher and it has worked fine until I began using bluetooth in my app.
When bluetooth tries to connect to a device it shows an alert window asking if the user wants to pair the device. This alert is enough to trigger the applicationWillResignActive method and then runs my code for when the app is being navigated away from (task switcher). This causes a large problem since the code I intend to run when switching away, turns off some much needed functionality within the actual app. So once they press "pair" or "cancel" on that alert, all of my app stops functioning as it should because the app has lost focus.
I have tried to detect the state of the application during this time with this... NSUInteger state = [[UIApplication sharedApplication] applicationState]; thinking of course that it would be considered active when the alert pops up and inactive when in the task switcher. However, this was not the case it shows up as active for both use cases.
Update #1
The question...
How can I differentiate in the application between the app causing a system level inactive focus state like running code to connect to bluetooth, versus the user causing the system level inactive focus like double tapping the home button? All in the efforts to distinguish what is causing the applicationWillResignActive method to fire.
Update #2
The intention of this functionality is to set a flag in NSUserDefaults when bluetooth connects to the device. This flag is being "observed" and used to trigger the changing of view controllers to a page related to this new BT connection. When the user double presses the home button and moves to task switcher I turn off BT and switch to iBeacon so I can notify of events. All is well with this current implementation all bar 1 use case.
If the user hasn't yet connected to the BT device and it connects for the first time and that pairing alert comes up it fires the applicationWillResignActive method just the same as double tapping the home button does. In this method the code then checks for that NSUserDefaults flag to see if it switched on (which by this time it is because the BT has already reached the CBCentralManager's didConnectPeripheral method and turned it on) and if it's on, it turns off BT and switched to scanning for iBeacon. Because the app is still open this obviously causes problems. The app is running so the user see's the BT connect, the new view slide in, the pairing alert come up, then the new view slide right back out and iBeacon starts sending notifications intended for when the user is in the task switcher.
I already have this exact functionality happening in the applicationWillEnterBackground method so that's not the answer. I need to have a way of saying "the app is running right now and we've received an alert instead of double tapping home, so please don't turn off BT and turn on iBeacon yet"
Two possible solutions:
1. The answer may lie in this statement:
When bluetooth tries to connect to a device it shows an alert window asking if the user wants to pair the device.
Your app must do something to cause this alert to appear. You could set a Date field to the current time in your AppDelegate when this happens, and then when you get a call to applicationWillResignActive you can compare that timestamp to the current time, and if it is < 1 second or so, you have a pretty good clue that the bluetooth dialog went up.
Of course, this is not foolproof. As #danh notes in his comment, the design of iOS makes this really difficult. You won't know for sure if the bluetooth dialog went up, or if the user or OS just happened to bring something else to the foreground at the same time. What's more, it's always possible that even if the bluetooth dialog comes up, the user might decide at that very moment to go check his or her email or start browsing Facebook. In that case, it is both true that the bluetooth dialog is what sent your app to the background, AND the user navigated away from the app. Unfortunately, iOS doesn't really give you a way to differentiate the two.
2. You might use a background task to handle your cleanup logic.
You can request up to 180 seconds of background running time after the call to applicationWillResignActive, so you could defer your cleanup tasks until say 175 seconds have passed since your app is resigned to the background. If the user doesn't come back within 3 minutes, it's probably time to do this cleanup anyway. My blog post here shows the basics of setting up a background task. It is specifically targeted to extending beacon ranging time, but you can put whatever logic you want inside the background code block like this:
- (void)extendBackgroundRunningTime {
if (_backgroundTask != UIBackgroundTaskInvalid) {
// if we are in here, that means the background task is already running.
// don't restart it.
return;
}
NSLog(#"Attempting to extend background running time");
__block Boolean self_terminate = YES;
_backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithName:#"DummyTask" expirationHandler:^{
NSLog(#"Background task expired by iOS");
if (self_terminate) {
[[UIApplication sharedApplication] endBackgroundTask:_backgroundTask];
_backgroundTask = UIBackgroundTaskInvalid;
}
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Background task started. Waiting 175 seconds before cleanup.");
[NSThread sleepForTimeInterval:175];
//TODO: perform cleanup code if app is not in the foreground by now
});
}
Is a valid, even in case of an authentication error?
GKLocalPlayer.localPlayer.authenticateHandler =
^(UIViewController *viewController, NSError *error)
{
if (error)
{
bool a = GKLocalPlayer.localPlayer.authenticated;
}
else
{
This happens for instance when I have an authenticated player, moves the app to the background, disables the WiFi, and then move the app to foreground again. My hope is that GameCenter just continues with a cached account?
I find the manual a bit ambiguous.
From https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/GameKit_Guide/Users/Users.html#//apple_ref/doc/uid/TP40008304-CH8-SW11:
"As soon as your game moves to the background, the value of the local player object’s authenticated property becomes and remains invalid until your game moves back to the foreground. You cannot read the value to determine if the player is still authenticated until Game Kit reauthenticates the player and calls your authentication handler. Your game must act as though there is not an authenticated player until your completion handler is called. Once your handler is called, value stored in the authenticated property is valid again."
Is the value valid even though the authentication failed?
I have a long-running Bug with Apple on this. It's been closed and re-opened during the ongoing dialog. The question of whether or not .authenticated is valid seems to depend on your perspective
Apple views this as working-as-intended as you have cached information which Apple believes lets you go ahead and play your game, you can display leaderboards, etc. Apple says that .authenticated is indeed valid in this state. I've seen some developers on this forum agree with that perspective, although I don't have links handy to their posts.
In practice, though, if you attempt to do any subsequent game center operation while in this state, it will fail because you're not really authenticated. You can't save games, load matches, etc. Any leaderboard you display will be stale, cached data.
It appears to me that Apple loathes for players to ever see a problem resulting from their infrastructure. Thus, with this mechanism you attempt to drive forward by faking the state, hoping the problem works itself out later. In my games, that strategy never pans out and eventually reaches an unrecoverable situation after users have invested time/effort into the game. So, like your code above, I rely on what the NSError says. If is says "error" then I treat the player as unathenticated, providing UI prompts to correct the situation.
I've documented more details on my approach here: https://stackoverflow.com/a/37216566/1641444
I have a Game Center game that allows players to make multiple moves per turn. In iOS 6, Apple implemented a great feature in saveCurrentTurnWithMatchData that allows you to do just that- it saves the data to game center to prevent cheating by repeatedly redoing a move for instance, without advancing to the next player.
The problem is, I have discovered that this actually triggers the same Push Notification taht gets sent when the player does end their turn. So other players in the game will see a badge on the app's icon and mistakenly think it's their turn when it isn't.
Has anyone found a workaround for this? Any way to call saveCurrentTurnWithMatchData without sending a push notification? If not, this seems like a design flaw that should probably be brought to Apple's attention.
I agree, this seems like a design flaw. I am also developing a turn-based game whereby a player can take several actions before passing control over to the next player. Meanwhile, I want other players to witness every action while they are looking at the game. If the other players are not running the app, I want them to receive a push notification only when the control is passed to another player.
Instead of using saveCurrentTurnWithMatchData:, I use endTurnWithNextParticipants: but I specify the current player rather than the next. This seems to do the trick:
NSTimeInterval interval = 86400; // seconds in a day
[currentMatch
endTurnWithNextParticipants:[[NSArray alloc] initWithObjects:currentMatch.currentParticipant,nil]
turnTimeout:interval matchData:[self packMatchData]
completionHandler:^(NSError *error) {
if (error) {
// handle error
}
}
];
I am using iOS 6 Game Center API for turn based games.
When the device is disconnected from internet
In the completion handler of the method
[currentMatch endTurnWithNextParticipant:nextParticipant matchData:data completionHandler:^(NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
//save the new state of the game
}
I get an error. But then, game center standard UI that displays matches list, says "Their turn". when connected again it changes to "Your turn".
The code from famous tutorial at http://www.raywenderlich.com/5509/beginning-turn-based-gaming-with-ios-5-part-2 has the same exact problem.
How I should handle this problem?
If you are using iOS 6 Game Center API then you will have to use
-endTurnWithNextParticipants:turnTimeout:matchData:completionHandler:
because...
–endTurnWithNextParticipant:matchData:completionHandler: Deprecated in iOS 6.0
http://developer.apple.com/library/ios/#documentation/GameKit/Reference/GKTurnBasedMatch_Ref/Reference/Reference.html
The thing is, that when you use GC methods that change status of the match (matchData and synchronization info in this case), data is uploaded to the GC server so that other player(s) get the update. If you're disconnected and ignore the error, your local GKTurnBasedMatch and its matchData change, as well as your synchronization info (which is used to determine if it is your turn to act among other things).
However, since you are diconnected, only your local instance of GCTurnBasedMatch is updated (you get error so that you app is aware of that). When you're reconnected, your app authenticates the user and updates match state (if you're following the tutorial code). Updating match data reverts the sync data (so it's still your turn).
At this point, you should either submit the turn again (provided that you cached gameData that was passed to GC while you were disconnected) and/or call updateMatchData so that your local GKTurnBasedMatch and its matchData get in sync with what's on the server. You should also re-layout your game board with previous turn's data if you didn't re-submit turn after reconnection.