OGeek|极客世界-中国程序员成长平台

标题: iOS 应用程序在 UIGraphicsEndPDFContext() 崩溃 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:33
标题: iOS 应用程序在 UIGraphicsEndPDFContext() 崩溃

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

func createPdfFromView(saveToDocumentsWithFileName fileName: String) -> 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 + "/" + fileName
        debugPrint(documentsFileName)
        pdfData.write(toFile: documentsFileName, atomically: true)
        let localUrl  = "file://"+documentsFileName as CFString
        let pdfDocumentRef = CFURLCreateWithFileSystemPath(nil, localUrl, CFURLPathStyle.cfurlposixPathStyle, false)
        pdfDoc = CGPDFDocument(pdfDocumentRef!)
        return pdfDoc
    }

    return nil
}

但我的应用程序经常崩溃 UIGraphicsEndPDFContext() 出现 EXC_BAD_ACCESS 错误。不知道为什么会这样。我是 Swift 新手。



Best Answer-推荐答案


对我来说,这发生在我也试图用 CGContextRelease 释放它之后:

UIGraphicsEndPDFContext();
CGContextRelease(pdfContext);//<-comment out this to solve

我只需要 UIGraphicsEndPDFContext(); 由于某种原因,即使在调用 EndPDFContext 之后调用 CGContextRelease,仍然会导致 EndPDFContext 行出现 EXC_BAD_ACCESS,这可能是一个异步问题。

关于iOS 应用程序在 UIGraphicsEndPDFContext() 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45839827/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4