在Swift中创建CSV文件并写入文件 [英] Create CSV file in Swift and write to file

查看:590
本文介绍了在Swift中创建CSV文件并写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它有 UITableView todoItems 作为 array 。它工作正常,我有一个导出按钮,从 UITableView 数据创建一个CSV文件,并发出电子邮件:

I have an app I've made that has a UITableView with todoItems as an array for it. It works flawlessly and I have an export button that creates a CSV file from the UITableView data and emails it out:

// 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文件列表。有人可以帮忙吗?谢谢!

My question is how do I create the same CSV file, but instead of emailing, save it to file? I'm new to programming and still learning Swift 2. I understand that the section of code (data!, mimeType: "text/csv", fileName: "TodoList.csv") creates the file as an attachment. I've looked online for this and trying to understand paths and directories is hard for me. My ultimate goal is to have another UITableView with a list of these 'saved' CSV files listed. Can someone please help? Thank you!

我在我的专案中加入了以下 IBAction

I added the following IBAction to my project:

// 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 {

    }

}


推荐答案

convertMutable 可以很容易地写入磁盘与 fun writeToFile(_ path:String,atomically useAuxiliaryFile:Bool,enc:UInt)throws func writeToURL(_ url:NSURL,atomically useAuxiliaryFile:Bool,enc:UInt)throws 。所有你需要做的是创建一个路径或URL将字符串写入。如果你使用iCloud的东西会更具挑战性,但对于本地存储的文件,你可以使用 let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as NSString 获取文档目录的根路径。

convertMutable can be easily written to disk with either fun writeToFile(_ path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws or func writeToURL(_ url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws. All you have to do is create a path or URL to write the string out to. If you are using iCloud things will be more challenging but for locally stored files you can use let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString to get the root path of the documents directory.

更新:根据您在此处的第一条评论,添加了一些信息:
第一个问题是,它看起来好像你正在寻找代码,你可以只粘贴你的项目,而不真正理解它的作用。我的观点,如果我错了,但如果我是对的,这不是一个好的路线,因为你会有很多问题在路上,当事情发生变化。

Update: Based on you first comment below here is some added info: The first issue is that it appears as though you are looking for code you can just paste int your project without really understanding what it does. My appologies if I'm wrong, but if I'm right this is not a good route to take as you will have many issues down the road when things change.

在最后一个代码段的底部,你试图在一个函数内部创建一个函数,它不会做你想要的。上面提到的函数是两个NSString函数的声明,而不是你需要创建的函数。由于NSMutableString是NSString的子类,因此您可以在 convertMutable 变量上使用这些函数。

At the bottom of your last code section you are trying to create a function inside a function which is not going to do what you want. The above mentioned functions are the declarations of two NSString functions not functions that you need to create. As NSMutableString is a subclass of NSString you can use those functions on your convertMutable variable.

处理是为您要保存的文件创建名称,当前您在上面的行中粘贴了获取Documents目录但没有文件名的文件。您需要设计一种方法,在每次保存CSV文件时创建唯一的文件名,并将该名称添加到 path 的末尾。然后您可以使用 writeToFile ... writeToURL ... 将字符串写入所需位置。

Another thing you need to deal with is creating a name for the file you want to save, currently you have pasted in the line above that gets the Documents directory but does not have a file name. You will need to devise a way to create a unique filename each time you save a CSV file and add that name to the end of path. Then you can use writeToFile… or writeToURL… to write the string to the desired location.

如果你发现你不完全理解你正在添加的代码,那么考虑拿一本书或者找到关于Swift的类(Coursera.org有一个可能有用的类)。有大量的资源在那里学习软件开发的基础知识和Swift,它将花费精力和时间,但如果这是你想要的东西,它将是值得的。

If you find you don't fully comprehend the code you are adding then consider getting a book or finding classes about Swift (Coursera.org has a class that may be of use). There are plenty of resources out there learn the basics of software development and Swift, it will take effort and time but it will be worth it in the end if this is something you want to pursue.

这篇关于在Swift中创建CSV文件并写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆