Hi everyone, I use this method for render a SwiftUI view to a PDF, My method is work and my app not crashing but I got errors on the debug area. The errors appearing exactly when I tap ShareLink button.
my code:
struct ContentView: View {
var body: some View { ...
// Rest of the codes
}
}
.navigationTitle("")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup {
ShareLink("Export PDF", item: render())
}
}
}
func render() -> URL {
// 1: Render Hello World with some modifiers
let renderer = ImageRenderer(content: PdfView)
// 2: Save it to our documents directory
let url = URL.documentsDirectory.appending(path: "test.pdf")
// 3: Start the rendering process
renderer.render { size, context in
// 4: Tell SwiftUI our PDF should be the same size as the views we're rendering
var box = CGRect(x: 0, y: 0, width: size.width, height: size.height)
// 5: Create the CGContext for our PDF pages
guard let pdf = CGContext(url as CFURL, mediaBox: &box, nil) else {
return
}
// 6: Start a new PDF page
pdf.beginPDFPage(nil)
// 7: Render the SwiftUI view data onto the page
context(pdf)
// 8: End the page and close the file
pdf.endPDFPage()
pdf.closePDF()
}
return url
}
var PdfView: some View { ...
// Rest of the code
}
}
}
}
Errors :
How I can solve that?
Thanks in advance