问题
I have content stored in String variable in my app and I want to save it as a file to the Files app. Well, it's easy and described for example here Save document to "Files" App in swift but I'm wondering whether is it possible to assign custom name to the file. iOS assigns implicit name Text.txt. Thanks.
回答1:
@IBAction func btnExportData(_ sender: Any) {
let prompt = UIAlertController(title: "Export data for counter", message: "Provide file name:", preferredStyle: .alert)
prompt.addTextField {(textField) in textField.text = ""}
prompt.addAction(UIAlertAction(title: "Export", style: .default, handler: {
(_) in
do {
let export = try self.objMeasurements.exportData(forCounterID: self.counterID)
let fm = FileManager.default
let fileFolder = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = fileFolder.appendingPathComponent(prompt.textFields![0].text! + ".csv")
do {
try export.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
self.showOkAlert(messageTitle: "File " + fileURL.absoluteString + " can't be created.", messageText: "Method: btnExportData", okText: "OK", {})
}
let sharing = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
sharing.completionWithItemsHandler = {
(type, completed, items, error) in
do {
try fm.removeItem(at: fileURL)
self.showOkAlert(messageTitle: "Temporary file was successfully deleted.", messageText: fileURL.absoluteString, okText: "OK", {})
} catch {
self.showOkAlert(messageTitle: "File " + fileURL.absoluteString + " can't be deleted.", messageText: "Method: btnExportData", okText: "OK", {})
}
}
sharing.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItems?.first
self.present(sharing, animated: true, completion: nil)
} catch measurementErrors.measurementGetFailed(let message) {
self.showOkAlert(messageTitle: message[0], messageText: message[1], okText: "OK", {})
} catch counterErrors.counterGetFailed(let message) {
self.showOkAlert(messageTitle: message[0], messageText: message[1], okText: "OK", {})
} catch elementErrors.elementGetFailed(let message) {
self.showOkAlert(messageTitle: message[0], messageText: message[1], okText: "OK", {})
} catch {
self.showOkAlert(messageTitle: "Unknown error during data export", messageText: "Method: btnExportData", okText: "OK", {})
}
}))
prompt.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(prompt, animated: true, completion: nil)
}
来源:https://stackoverflow.com/questions/54026866/how-to-name-file-stored-to-files-app-via-uactivityviewcontroller