ShareLink and PDFDocument

Dear All,

How do I share a PDFDocument using the new ShareLink of the SwiftUI?

The following code does not compute:

let pdf = PDFDocument(data: data)
ShareLink(items: pdf.dataRepresentation()!)

Thanks.

Answered by tomas.bek in 719230022

So I managed to get it working by extending PDFDocument. This is not a super clean solution, so please feel free to improve it further in the comments!

extension PDFDocument: Transferable {
    public static var transferRepresentation: some TransferRepresentation {
        DataRepresentation(contentType: .pdf) { pdf in
                if let data = pdf.dataRepresentation() {
                    return data
                } else {
                    return Data()
                }
            } importing: { data in
                if let pdf = PDFDocument(data: data) {
                    return pdf
                } else {
                    return PDFDocument()
                }
            }
        DataRepresentation(exportedContentType: .pdf) { pdf in
            if let data = pdf.dataRepresentation() {
                return data
            } else {
                return Data()
            }
        }
     }
}

And then you can share the PDF document like this:

if let document = document {
         ShareLink(item: document, preview: SharePreview("PDF"))
}

I'd like to know how to share a file as well!

Accepted Answer

So I managed to get it working by extending PDFDocument. This is not a super clean solution, so please feel free to improve it further in the comments!

extension PDFDocument: Transferable {
    public static var transferRepresentation: some TransferRepresentation {
        DataRepresentation(contentType: .pdf) { pdf in
                if let data = pdf.dataRepresentation() {
                    return data
                } else {
                    return Data()
                }
            } importing: { data in
                if let pdf = PDFDocument(data: data) {
                    return pdf
                } else {
                    return PDFDocument()
                }
            }
        DataRepresentation(exportedContentType: .pdf) { pdf in
            if let data = pdf.dataRepresentation() {
                return data
            } else {
                return Data()
            }
        }
     }
}

And then you can share the PDF document like this:

if let document = document {
         ShareLink(item: document, preview: SharePreview("PDF"))
}
ShareLink and PDFDocument
 
 
Q