首页 > 解决方案 > App crashes on CGContext.drawPDFPage with a EXC_BAD_ACCESS

问题描述

My app is randomly crashing on CGContext.drawPDFPage without a way to reproduce the bug consistently. It happens mostly on iPads. The code looks something like this:

override func draw(_ layer: CALayer, in ctx: CGContext) {

  UIGraphicsPushContext(ctx)
  ctx.saveGState()

  defer {
    ctx.restoreGState()
    UIGraphicsPopContext()
  }

  ctx.setFillColor(UIColor.white.cgColor)
  ctx.fill(viewBounds)

  ctx.translateBy(x: 0, y: viewBounds.height)
  ctx.scaleBy(x: 1, y: -1)
  ctx.scaleBy(x: pdfScale, y: pdfScale)

  ctx.interpolationQuality = .high
  ctx.setRenderingIntent(.defaultIntent)

  ctx.beginPDFPage(nil)
  ctx.drawPDFPage(pdfPage) // This is where the crash happens
  ctx.endPDFPage()
}

The stack trace ends in CGPDFObjectGetReference and looks like this:

Stack

The error is: EXC_BAD_ACCESS. If you see anything that could be causing this crash would help me a lot!

标签: iosswiftipadcgcontext

解决方案


iOS 12

任何遇到类似崩溃的人,情况都在缓存层中,按索引请求CGPDFDocumentCGPDFPage在特定情况下。

解决方案是按需从持久存储请求 PDF。

iOS 13

从 iOS 13 开始——我们没有看到任何与此相关的错误,因此 Apple 可能通过从值CGPDFDocumentCGPDFPage类型恢复上下文来解决该错误。


推荐阅读