Set filename to use for "Save to Files" with ShareLink?

Isn't there no way to set the default filename to use when we want to save a DataRepresentation to a file?

If I export to JSON, the filename is "JSON.json" is used by iOS, even if I set the name to use in SharePreview.

struct ContentView: View {

    let car = Car(id: UUID(), name: "911", items:

                    [Item(id: UUID(),date: .now, desc: "oil change"),

                     Item(id: UUID(),date: .now, desc: "Battery")])

    var body: some View {

        VStack {

            ShareLink(item: car, preview: SharePreview(car.name))

        }

        .padding()

    }

}

extension UTType {

    static var car: UTType = UTType(exportedAs: "com.acme.cararchive")

}

struct Car: Codable {

    let id: UUID

    let name: String

    let items: [Item]

}



extension Car: Transferable {

    static var transferRepresentation: some TransferRepresentation {

        DataRepresentation(contentType: .json) { archive in

            try JSONEncoder().encode(archive)

        } importing: { data in

            try JSONDecoder().decode(Car.self, from: data)

        }

    }

}



struct Item: Codable {

    let id: UUID

    let date: Date

    let desc: String

}

Additionally, if I use my custom type instead of .json when exporting, the "Save to Files" doesn't even show up, even if I did set the export type in the info.plist file.

extension UTType {

    static var car: UTType = UTType(exportedAs: "com.acme.cararchive")

}

extension Car: Transferable {

    static var transferRepresentation: some TransferRepresentation {

        DataRepresentation(contentType: .car) { archive in

            try JSONEncoder().encode(archive)

        } importing: { data in

            try JSONDecoder().decode(Car.self, from: data)

        }

    }

}

fefe

Ok so I made some progress. Turns out I was using com.public.data instead of public.data in Exported Type Identifier > Conform To.

So now saving to files will use the proper file extension (.cararchive) I've set in Exported Type Identifier > Extensions.

However, the filename defaults to what I've set in Exported Type Identifier > Description. I'd like to set a default name myself as the one used by iOS makes no sense.

Did you try this method?

Using the above, I was able to customize the filename for all exports. However, I didn’t manage to set a filename that depends on the item I’m exporting. But maybe it solves your specific problem.

That kinda helps however, the function that generates the transferrable data is a static function meaning that the filename most appropriate for the data is not available to the wrapper... Also, the new link to that method is: https://developer.apple.com/documentation/coretransferable/transferrepresentation/suggestedfilename(_:)-2yln2

Set filename to use for "Save to Files" with ShareLink?
 
 
Q