简体   繁体   中英

Creating a temporary txt file, from a String, to use as an NSSharingService item?

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 = ["help@email.com"]
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!

Swift 5.2

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")

Conclusion: NSSharingService

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 = ["my@email.com"]
service?.subject = "Email Subject Title"
service?.perform(withItems: [messageContents, txtFile])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM