菜鸟教程小白 发表于 2022-12-11 18:33:22

iOS 应用程序在 UIGraphicsEndPDFContext() 崩溃


                                            <p><p>我正在尝试从当前 View 创建 PDF。下面是我的代码。</p>

<pre><code>func createPdfFromView(saveToDocumentsWithFileName fileName: String) -&gt; CGPDFDocument?
{
    let pdfData = NSMutableData()
    var pdfDoc: CGPDFDocument!
    UIGraphicsBeginPDFContextToData(pdfData, self.view.bounds, nil)
    UIGraphicsBeginPDFPage()

    guard let pdfContext = UIGraphicsGetCurrentContext() else { return nil }

    self.view.layer.render(in: pdfContext)
    UIGraphicsEndPDFContext()

    if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
      let documentsFileName = documentDirectories + &#34;/&#34; + fileName
      debugPrint(documentsFileName)
      pdfData.write(toFile: documentsFileName, atomically: true)
      let localUrl= &#34;file://&#34;+documentsFileName as CFString
      let pdfDocumentRef = CFURLCreateWithFileSystemPath(nil, localUrl, CFURLPathStyle.cfurlposixPathStyle, false)
      pdfDoc = CGPDFDocument(pdfDocumentRef!)
      return pdfDoc
    }

    return nil
}
</code></pre>

<p>但我的应用程序经常崩溃
<code>UIGraphicsEndPDFContext()</code> 出现 EXC_BAD_ACCESS 错误。不知道为什么会这样。我是 Swift 新手。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>对我来说,这发生在我也试图用 CGContextRelease 释放它之后:</p>

<pre><code>UIGraphicsEndPDFContext();
CGContextRelease(pdfContext);//&lt;-comment out this to solve
</code></pre>

<p>我只需要 <code>UIGraphicsEndPDFContext();</code>
由于某种原因,即使在调用 EndPDFContext 之后调用 CGContextRelease,仍然会导致 <code>EndPDFContext</code> 行出现 EXC_BAD_ACCESS,这可能是一个异步问题。</p></p>
                                   
                                                <p style="font-size: 20px;">关于iOS 应用程序在 UIGraphicsEndPDFContext() 崩溃,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45839827/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45839827/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iOS 应用程序在 UIGraphicsEndPDFContext() 崩溃