Taking screenshots in cocos2d on iOS6

Many cocos2d developers have recently found that with the upgrade to iOS6 their screenshot code is no longer working. This is due to the fact that iOS now returns nothing when reading pixels from the frame buffer after it has been presented to the screen. Apple has warned that this was unsupported behaviour for a while, and it looks like they've finally acted on that. 

There is however a method that does work on iOS6 and that is to use a CCRenderTexture. The code is as follows.

-(UIImage*) screenshotWithStartNode:(CCNode*)startNode
{
[CCDirector sharedDirector].nextDeltaTimeZero = YES;

CGSize winSize = [CCDirector sharedDirector].winSize;
CCRenderTexture* rtx =
[CCRenderTexture renderTextureWithWidth:winSize.width
height:winSize.height];
[rtx begin];
[startNode visit];
[rtx end];

return [rtx getUIImage];
}

The code works by drawing a node, and all its children, into a CCRenderTexture. After this a UIImage is returned which can be saved into a file in your documents directory. 

To take a screenshot of the current scene, the method can be called with the following parameters.

CCScene *scene = [[CCDirector sharedDirector] runningScene];
CCNode *n = [scene.children objectAtIndex:0];
UIImage *img = [self screenshotWithStartNode:n];

There you have it, a screenshot on iOS6!