我的内容存储在应用程序的String变量中,我想将其另存为文件到“文件”应用程序。好吧,这很容易,例如在Save document to "Files" App in swift中进行了描述,但我想知道是否可以为文件分配自定义名称。 iOS分配隐式名称Text.txt。 谢谢。
答案 0 :(得分: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)
}