In my app, I'd like to be able to share a .csv file via ShareLink
and Transferable
. I watched the "Meet Transferable" WWDC22 video and it should be possible as the presenter demonstrated that use case.
However, when I try this on my end, I am able to share the content but somehow it is treated by iOS as plaintext and when sharing by email or messages, it will just add the text content to the body.
If I try to share via AirDrop, it creates a random filename with the .txt extension even though I specify .commaSeparatedText
.
The only way this somewhat works is when saving to files. It will save as a .csv file but the filename is set to "comma-separated values".
Here's some code:
struct MyArchive {
enum ValidationError: Error {
case invalid
}
var filename: String {
return "myarchive.csv"
}
init(csvData: Data) throws {
//...
}
func convertToCSV() throws -> Data {
let test = "Name,Email\nPete,pete@example.com"
if let data = test.data(using: .utf8) {
return data
}
else {
throw ValidationError.invalid
}
}
}
extension MyArchive: Transferable {
static var transferRepresentation: some TransferRepresentation {
DataRepresentation(contentType: .commaSeparatedText) { archive in
try archive.convertToCSV()
} importing: { data in
try MyArchive(csvData: data)
}
}
}
And in my View
:
struct View: View {
var body: some View {
//...
let csv = MyArchive()
ShareLink(
item: csv,
preview: SharePreview(
csv.filename,
image: Image(systemName: "doc.plaintext")
)
)
}
}
I'm at the point that I wonder if I'm doing something wrong or this just doesn't work in iOS 16 beta 1.
Any hints?
Thanks!