5

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...?

4

2 に答える 2

8

-renderInContext:はスレッドセーフではなく、バックグラウンド スレッドから呼び出すことはできません。メインスレッドで描画を行う必要があります。

于 2013-02-28T12:19:10.930 に答える
3

メインスレッドでこのメソッドを実行する以外に何もすることはありませんでした。私はスレッド管理を再編成し、これを行うことで良い結果を得ることができました:

[self performSelectorOnMainThread:@selector(captureScreenOnMainThread) withObject:nil waitUntilDone: YES];場合によっては、最後のパラメーターを no に設定できます...

すべての応答に感謝します。

于 2013-04-25T09:11:40.740 に答える