SwiftUI ShareLink 设置文件名

Pat*_*ick 12 swift swiftui swiftui-sharelink core-transferable

我正在使用 来ShareLink共享FileDocument包含字符串的。符合FileDocument协议Transferable

这是 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()
  }
}
Run Code Online (Sandbox Code Playgroud)

这是共享链接:

var doc: TransferableDocument
{
    return TransferableDocument(initialText: "I'm a String")
}

ShareLink(item: doc ,preview: SharePreview("logfile")) 
{
    Text("Share")
}
Run Code Online (Sandbox Code Playgroud)

使用 AirDrop 时,文件名设置为 SharePreview 标题,在本例中为“logfile”。将其共享到“邮件”等应用程序时,文件名只需设置为“文本”。

有什么办法可以设置默认文件名吗?

Bug*_*ter 2

我们遇到了类似的问题,并在保存数据时配置了适当的文件名,并在函数中FileRepresentation添加了一个附加项。transferRepresentation当共享到邮件时,使用适当的文件名。

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)
    }
}
Run Code Online (Sandbox Code Playgroud)