当用户遇到意外错误时,我将向他们提供将错误日志内容作为NSSharingService项的电子邮件体发送的选项:
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])是否有一种使用临时文件引用将错误日志内容作为附加文本文件发送的有效方法;而不是必须使用目录和权限?与…有关的东西:
let txtFile = String(errorLog) as? file(name: "ErrorLog", withExtension: "txt")
service?.perform(withItems: [txtFile])Swift一直让我惊讶于它的一些实现是如此的简单和容易,所以我想我会问。
谢谢!
发布于 2022-09-04 18:57:13
Swift 5.2
更新日期:2022年9月4日
使用找到的解决方案这里,我能够使用FileManager.default.temporary创建一个字符串扩展。
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
}
}可以从任何字符串调用的;
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
总之,最终看起来会是这样的:
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])https://stackoverflow.com/questions/73601222
复制相似问题