objective c renderInContext crash on background thread

与世无争的帅哥 提交于 2019-12-05 01:40:37

问题


I have an app in which the screen continuously is capturing in background thread. 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 good for capturing once or twice. But after a while the app crashes always on the same line [[keyWindow layer] renderInContext:context]; and it gives EXC_BAD_ACCESS (code=1, address=0x8) message. I searched everywhere and nothing useful. Found only that renderInContext has memory leak issue when it works in background thread. But as you understand that doesn't solve my issue :) . So have 3 questions :-

  1. What is the reason of this crash (problem)?

  2. What can I do with this?

  3. Is there any other way to capture screen (beside the one that Apple suggests, because there renderInContext is also used). Something without rendering...?


回答1:


-renderInContext: is not thread-safe and you can't call it from a background thread. You'll have to do the drawing on the main thread.




回答2:


I had nothing to do but performing this method on main thread. I reorganized my thread management and could get good result for me doing this:

[self performSelectorOnMainThread:@selector(captureScreenOnMainThread) withObject:nil waitUntilDone: YES]; Last parameter can be set to no in some cases...

Thanks for all responses.



来源:https://stackoverflow.com/questions/15135208/objective-c-renderincontext-crash-on-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!