[英]SwiftUI ShareLink set file name
I'm using the ShareLink
to share an FileDocument
which contains a String.我正在使用
ShareLink
共享包含字符串的FileDocument
。 The FileDocument
is conform to the Transferable
protocol. FileDocument
符合Transferable
协议。
This is the FileDocument Struct:这是 FileDocument 结构:
struct TransferableDocument: FileDocument, Transferable {
static var transferRepresentation: some TransferRepresentation
{
DataRepresentation(exportedContentType: .text) { log in
log.convertToData()
}
}
// tell the system to support only text
static var readableContentTypes: [UTType] = [.text]
// by default the document is empty
var text = ""
// this initializer creates a empty document
init(initialText: String = "") {
text = initialText
}
// this initializer loads data that has been saved previously
init(configuration: ReadConfiguration) throws {
if let data = configuration.file.regularFileContents {
text = String(decoding: data, as: UTF8.self)
}
}
// this will be called when the system wants to write the data to disk
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let data = Data(text.utf8)
return FileWrapper(regularFileWithContents: data)
}
func convertToData() -> Data
{
return text.data(using: .ascii) ?? Data()
}
}
And this is the ShareLink:这是 ShareLink:
var doc: TransferableDocument
{
return TransferableDocument(initialText: "I'm a String")
}
ShareLink(item: doc ,preview: SharePreview("logfile"))
{
Text("Share")
}
When using AirDrop, the filename is set to the SharePreview title, in this case "logfile".使用 AirDrop 时,文件名设置为 SharePreview 标题,在本例中为“logfile”。 When sharing it to Apps like Mail, the filename is simply set to "text".
将其共享到 Mail 等应用程序时,文件名只需设置为“文本”即可。
Is there any way to set a default filename?有没有办法设置默认文件名?
We had a similar issue and added an additional FileRepresentation
to the transferRepresentation
func with the appropriate file name configured when saving out the data.我们遇到了类似的问题,并向
transferRepresentation
函数添加了一个额外的FileRepresentation
,并在保存数据时配置了适当的文件名。 With that in place when shared to Mail the appropriate file name was used.当共享到 Mail 时,使用适当的文件名。
static var transferRepresentation: some TransferRepresentation
{
DataRepresentation(exportedContentType: .text) { log in
log.convertToData()
}
FileRepresentation(exportedContentType: .text) { log in
let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("logfile").appendingPathExtension("txt")
try log.convertToData().write(to: fileURL)
return SentTransferredFile(fileURL)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.