Object c renderInContext crashing on background thread

I have an application in which the screen continuously captures the background stream. Here is the code

- (UIImage *) captureScreen { UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; CGRect rect = [keyWindow bounds]; UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [[keyWindow layer] renderInContext:context]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIDeviceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight) || (orientation==UIInterfaceOrientationPortraitUpsideDown)) { img=[self rotatedImage:img]; } return img; } 

It works well to capture once or twice. But after a while, the application crashes always in one line [[keyWindow layer] renderInContext:context]; , and it gives the message EXC_BAD_ACCESS (code=1, address=0x8) . I searched everywhere and nothing useful. I only found that renderInContext has memory leak problems when it is running in the background thread. But, as you know, this does not solve my problem :). So you have 3 questions: -

  • What is the cause of this failure (problem)?

  • What can i do with this?

  • Is there any other way to capture the screen (next to what Apple offers, since renderInContext is also used there). Something without rendering ...?

+4
source share
2 answers

-renderInContext: not thread safe, and you cannot call it from a background thread. You will need to draw a drawing on the main thread.

+8
source

I have nothing to do but execute this method in the main thread. I reorganized the flow control and could get a good result for me:

[self performSelectorOnMainThread:@selector(captureScreenOnMainThread) withObject:nil waitUntilDone: YES]; In some cases, the last parameter may be set to none ...

Thanks for all the answers.

+3
source

All Articles