ios - 如何在后台队列上渲染上下文?

标签 ios objective-c uiviewcontroller

我正在尝试制作 UIView 的快照。我用“标准”的东西来做这件事,但是,当我制作高性能应用程序时,我想在后台队列上运行它。我知道从后台线程 UIKits 调用是不好的。

在这种方法中,我尝试四处走动并捕捉图层:

    -(void)caps{

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, .1 * NSEC_PER_SEC);

    dispatch_queue_t myQueue = dispatch_queue_create("com.myapp.shot", NULL);

         dispatch_after(popTime, myQueue, ^(void){
             [self capture];

         });
}



-(void)capture{
    NSLog(@"Start");
    float height;
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    if(orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight){
        height = 600;
    }else{
        height = 500;
    }
     dispatch_async(dispatch_get_main_queue(), ^{
  /// in .h @property CALayer *liar;
         if (!self.liar) {
             self.liar = myWebView.scrollView.layer;
             NSLog(@"MAIN THREAD %@", self.liar);
         }

     });
    UIGraphicsBeginImageContext(CGSizeMake(self.view.frame.size.width, height));

    NSLog(@"NEw THREAD %@", self.liar);
    [self.liar renderInContext:UIGraphicsGetCurrentContext()];

    self.sharedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    NSLog(@"Finish %@", self.sharedImage);
}

大多数情况下它工作正常,但在某些情况下(当 myWebViewUIViewController 不可见时 - 浏览器选项卡将其隐藏)它会抛出错误:

bool _WebTryThreadLock(bool), 0x1adb1730: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
1   0x35f3b435 WebThreadLock
2   0x305b0b31 <redacted>
3   0x305b09ed <redacted>
4   0x305b0769 <redacted>
5   0x305b02cb <redacted>
6   0x30561353 <redacted>
7   0x301e7943 <redacted>
8   0x301e3167 <redacted>
9   0x30212425 <redacted>
10  0x30234f77 <redacted>
11  0x12f38f -[Browser capture]
12  0x12f10f __20-[Browser caps]_block_invoke
13  0x3896b0c3 <redacted>
14  0x3896fa47 <redacted>
15  0x3896c72f <redacted>
16  0x3896fe3d <redacted>
17  0x3896cf93 <redacted>
18  0x38970745 <redacted>
19  0x389709c5 <redacted>
20  0x38a9adff _pthread_wqthread
21  0x38a9acc4 start_wqthread

那么,出了什么问题,为什么如果 UIViewController 可见,它就可以完美地工作,而如果它为另一个 UIViewController 转换时会崩溃得如此严重?

最佳答案

除少数异常(exception)情况外,所有 UIKit 功能都明确地仅限于主线程。 许多UIGraphics~系列函数都是异常(exception)情况。反正其他的也不异常(exception)。我怀疑这些行可能会导致一些问题。

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

self.view.frame.size.width

然后,最好检查一下代码的其他部分是否意外调用了 UI~ 系列功能。

关于ios - 如何在后台队列上渲染上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24739551/

相关文章:

ios - UITableViewCellAutomaticDimension 行为异常

iphone - 麦克风和扬声器反馈

iphone - 如何跨 View Controller 共享 UIView 和其他元素?

ios - 如何在 UITableviewcells 中显示 HTML 颜色代码

ios - 返回 UITableViewController 时关闭 UIWebView

iOS - 使用 dealloc 删除观察者

ios - ionic Cordova 不能运行ios

ios - 如何检查一个区 block 是否实现?

ios - 应用自动布局后如何获取 UIImageView 大小?

ios - 如何在 Xcode 7 中启用_BITCODE?