gpt4 book ai didi

swift - 在 Swift 中创建 CSV 文件并写入文件

转载 作者:行者123 更新时间:2023-11-28 08:54:47 48 4
gpt4 key购买 nike

我有一个我制作的应用程序,它有一个 UITableViewtodoItems 作为它的 array。它工作完美,我有一个导出按钮,可以从 UITableView 数据创建一个 CSV 文件并将其通过电子邮件发送出去:

// Variables
var toDoItems:[String] = []
var convertMutable: NSMutableString!
var incomingString: String = ""
var datastring: NSString!

// Mail alert if user does not have email setup on device
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}

// CSV Export Button
@IBAction func csvExport(sender: AnyObject) {
// Convert tableView String Data to NSMutableString
convertMutable = NSMutableString();
for item in toDoItems
{
convertMutable.appendFormat("%@\r", item)
}

print("NSMutableString: \(convertMutable)")

// Convert above NSMutableString to NSData
let data = convertMutable.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
if let d = data { // Unwrap since data is optional and print
print("NSData: \(d)")
}

//Email Functions
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setSubject("CSV File Export")
mailComposerVC.setMessageBody("", isHTML: false)
mailComposerVC.addAttachmentData(data!, mimeType: "text/csv", fileName: "TodoList.csv")

return mailComposerVC
}

// Compose Email
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert() // One of the MAIL functions
}
}

我的问题是如何创建相同的 CSV 文件,而不是通过电子邮件将其保存到文件中?我是编程新手,仍在学习 Swift 2。我知道代码部分 (data!, mimeType: "text/csv", fileName: "TodoList.csv") 将文件创建为一个附件。我在网上查过这个,试图理解路径和目录对我来说很难。我的最终目标是让另一个 UITableView 列出这些“已保存”的 CSV 文件。有人可以帮忙吗?谢谢!

我将以下 IBAction 添加到我的项目中:

// Save Item to Memory
@IBAction func saveButton(sender: UIBarButtonItem) {
// Convert tableView String Data to NSMutableString
convertMutable = NSMutableString();
for item in toDoItems
{
convertMutable.appendFormat("%@\r", item)
}

print("NSMutableString: \(convertMutable)")

// Convert above NSMutableString to NSData
let data = convertMutable.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
if let d = data { // Unwrap since data is optional and print
print("NSData: \(d)")
}

let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString

func writeToFile(_: convertMutable, path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {

}

}

最佳答案

多年来,我一直在努力寻找一个像样的简单答案。

这是我发现的创建 csv 文件的最佳方法,甚至是您希望它成为的目录并写入它。

//First make sure you know your file path, you can get it from user input or whatever
//Keep the path clean of the name for now
var filePath = "/Users/Johnson/Documents/NEW FOLDER/"
//then you need to pick your file name
let fileName = "AwesomeFile.csv"
//You should probably have some data to put in it
//You can even convert your array to a string by appending all of it's elements
let fileData = "This,is,just,some,dummy,data"

// Create a FileManager instance this will help you make a new folder if you don't have it already
let fileManager = FileManager.default

//Create your target directory
do {
try fileManager.createDirectory(atPath: filePath!, withIntermediateDirectories: true, attributes: nil)
//Now it's finally time to complete the path
filePath! += fileName!
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

//Then simply write to the file
do {
// Write contents to file
try fileData.write(toFile: filePath!, atomically: true, encoding: String.Encoding.utf8)
print("Writing CSV to: \(filePath!)")
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

附言。刚刚注意到这个问题是一年前的,但我希望它能帮助像我这样苦苦挣扎的新手,当他们像我一样不可避免地偶然发现它时。

关于swift - 在 Swift 中创建 CSV 文件并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33349139/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com