首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字符串创建临时txt文件以用作NSSharingService项?

从字符串创建临时txt文件以用作NSSharingService项?
EN

Stack Overflow用户
提问于 2022-09-04 16:55:10
回答 1查看 28关注 0票数 0

当用户遇到意外错误时,我将向他们提供将错误日志内容作为NSSharingService项的电子邮件体发送的选项:

代码语言:javascript
复制
let errorLog = "[Extensive log output with many symbols and new lines]"
        
let service = NSSharingService(named: NSSharingService.Name.composeEmail)
service?.recipients = ["help@email.com"]
service?.subject = "Help: App Error"
service?.perform(withItems: [errorLog])

是否有一种使用临时文件引用将错误日志内容作为附加文本文件发送的有效方法;而不是必须使用目录和权限?与…有关的东西:

代码语言:javascript
复制
let txtFile = String(errorLog) as? file(name: "ErrorLog", withExtension: "txt")

service?.perform(withItems: [txtFile])

Swift一直让我惊讶于它的一些实现是如此的简单和容易,所以我想我会问。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2022-09-04 18:57:13

Swift 5.2

更新日期:2022年9月4日

使用找到的解决方案这里,我能够使用FileManager.default.temporary创建一个字符串扩展。

代码语言:javascript
复制
extension String {
  func createTxtFile(_ withName: String = "temp") -> URL {
    let url = FileManager.default.temporaryDirectory
      .appendingPathComponent(withName)
      .appendingPathExtension("txt")
    let string = self
    try? string.write(to: url, atomically: true, encoding: .utf8)
    return url
  }
}

可以从任何字符串调用的;

代码语言:javascript
复制
let myString = "My txt file contents"
// Creates a URL reference to temporary file: My-File-Name.txt
let txtFile = myString.createTxtFile("My-File-Name")

结论: NSSharingService

总之,最终看起来会是这样的:

代码语言:javascript
复制
let messageContents = "Email body with some newlines to separate this sentence and the attached txt file.\n\n\n"
let txtFileContents = "The contents of your txt file as a String"

// Create a URL reference to the txt file using the extension
let txtFile = txtFileContents.createTxtFile("Optional-File-Name")

// Compose mail client request with message body and attached txt file
let service = NSSharingService(named: NSSharingService.Name.composeEmail)
service?.recipients = ["my@email.com"]
service?.subject = "Email Subject Title"
service?.perform(withItems: [messageContents, txtFile])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73601222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档