Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpriteKit- the right way to multitask

I tried to search everywhere in the code:Explained documentry what it does when going to background, or if it is even paused sometime, but to no avail- can someone direct me in the way of what is recommended to do when going to background in sprite kit enabled game?

Should I just call scene.paused = YES, or how can I confirm that no drawing occurs in background so I can avoid termination by iOS which won't allow me that?

Thanks!

like image 721
Lior Pollak Avatar asked Sep 25 '13 19:09

Lior Pollak


1 Answers

SpriteKit really isn't documented that well yet, probably because it's so new that relatively few developers have implemented it. SpriteKit should pause animations when backgrounding, but in my experience (and harrym17's) it will cause memory access errors and quits the app entirely rather than backgrounding it.

According to the Apple Developer forums, it seems this is a known bug in SpriteKit (it doesn't always pause animations when backgrounding, as it should) causing memory access errors as per harrym17's comment. Here's a brief fix which has worked for me - my app was consistently crashing when backgrounding, and since adding this code everything works fine.

(Kudos to Keith Murray for this code on the Apple forums; as far as I can see he hasn't posted it on SO).

In AppDelegate.h, make sure you import SpriteKit:

#import <SpriteKit/SpriteKit.h>

In AppDelegate.m, edit your applicationWillResignActive method:

- (void)applicationWillResignActive:(UIApplication *)application
{
     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

     // pause sprite kit
     SKView *view = (SKView *)self.window.rootViewController.view;
     view.paused = YES;
}

And this to your applicationDidBecomeActive method:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

     // resume sprite kit
     SKView *view = (SKView *)self.window.rootViewController.view;
     view.paused = NO;
}

There are additional problems when backgrounding when playing audio via AVAudioSession, apparently; a workaround is mentioned in this thread.

like image 88
MassivePenguin Avatar answered Nov 27 '22 02:11

MassivePenguin