Reputation: 5558
When the user is confronted with an unexpected error, I'm providing them with the option to send the error log contents as an email body of an NSSharingService item as such:
let errorLog = "[Extensive log output with many symbols and new lines]"
let service = NSSharingService(named: NSSharingService.Name.composeEmail)
service?.recipients = ["[email protected]"]
service?.subject = "Help: App Error"
service?.perform(withItems: [errorLog])
Is there an efficient way to go about sending the error log contents as an attached text file, using temporary file references; as opposed to having to work with directories and permissions? Something along the lines of:
let txtFile = String(errorLog) as? file(name: "ErrorLog", withExtension: "txt")
service?.perform(withItems: [txtFile])
Swift has constantly surprised me with how simple and easy some of its implementation can be, so I thought I'd ask.
Thank you!
Upvotes: 1
Views: 472
Reputation: 5558
Updated: September 4, 2022
Using the solution found here, I was able to create a String extension using 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
}
}
Which can be called from any String; ie.
let myString = "My txt file contents"
// Creates a URL reference to temporary file: My-File-Name.txt
let txtFile = myString.createTxtFile("My-File-Name")
All together, this will end up looking something like:
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 = ["[email protected]"]
service?.subject = "Email Subject Title"
service?.perform(withItems: [messageContents, txtFile])
Upvotes: 2