【问题标题】:SwiftUI ShareLink set file nameSwiftUI ShareLink 设置文件名
【发布时间】:2023-01-17 10:40:40
【问题描述】:

我正在使用 ShareLink 共享一个包含字符串的 FileDocumentFileDocument 符合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()
  }
}

这是 ShareLink:

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

ShareLink(item: doc ,preview: SharePreview("logfile")) 
{
    Text("Share")
}

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

有没有办法设置默认文件名?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    我们遇到了类似的问题,并在 transferRepresentation 函数中添加了一个额外的 FileRepresentation,并在保存数据时配置了适当的文件名。当共享到 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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-19
      • 2022-11-15
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      相关资源
      最近更新 更多