获取 NSMutableString 并转换为 CSV 文件以用于电子邮件

Take NSMutableString and convert to CSV file for email

我正在尝试从 UITableView 中获取我的数据,即 var toDoItems:[String] = []。我正在尝试获取此数据并将其转换为 CSV 文件以便通过电子邮件发送。我找不到关于 Xcode 7 和 Swift 2 的任何当前信息。我找到的所有内容都是 Objective C。我是编程新手,所以尝试将 Objective C 转换为 Swift 2 对我来说很难。我和我的一个朋友谈过,他说把我的 UITableView 数据转换成 NSMutableString。然后将我的 NSMutableString 转换为 NSData。他说 NSData 可以写入 CSV 文件。

一段代码为:

// Helps to have it APPEAR when adding new items **
override func viewWillAppear(animated: Bool) {

    // Checks to see if there are any past items to boot up with
    if let storedtoDoItems : AnyObject = savedDefaults.objectForKey("toDoItems") {

        //If there are, it sets the array to nothing
        toDoItems = []

        for var i = 0; i < storedtoDoItems.count; ++i {
            toDoItems.append(storedtoDoItems[i] as! String)

            // Convert stored tableView data to string
            incomingString = String(toDoItems)
        }
    }
    tasksTable.reloadData()
}

我声明了以下变量:

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

这是我的导出按钮操作:

// PDF Button
@IBAction func pdfExport(sender: AnyObject) {

    // Convert tableView String Data to NSMutableString if needed
    convertMutable = NSMutableString(UTF8String: incomingString)
    print("NSMutableString: \(convertMutable)")

    // Convert tableView String Data to NSString if needed
    convertString = String(incomingString)
    print("NSString: \(convertString)")

    // Convert above NSString to NSData
    let data = convertString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    if let d = data { // Unwrap since data is optional and print
        print("NSData: \(d)")
    }
    // Convert NSData back to NSString to verify NSData was actual data and test
    datastring = NSString(data:data!, encoding:NSUTF8StringEncoding) as! String
    print("Back to NSString: \(datastring)")

}

有人可以帮我举例说明如何用 Swift 2 做到这一点吗?谢谢。

所以做了一些研究并弄明白了。

我输入的 @IBAction func 代码:

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

我还为邮件添加了这两个功能:

// 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 文件并将其附加到电子邮件中,打开准备好接收 'To' 地址的邮件应用程序。这是 Swift 2 和 Xcode 7.