我刚开始使用Swift(以及一般的编程),我正在尝试为我工作的公司创建一个简单的订单列表电子邮件应用程序。
我的应用程序的基础来自Envato Tuts + Swift购物清单教程。
我知道这已被问了一百万次,而且我已经尝试过,但是我不知道如何将我的UITableView
列表数据放到CSV文件中并附上它。
下面是我的ShoppingListViewController.swift文件内容,其中包含了一个按钮来启动MFMailComposeViewControllerDelegate
。
请有人请我走上正轨吗?
import UIKit
import MessageUI
import Foundation
class ShoppingListViewController: UITableViewController, MFMailComposeViewControllerDelegate{
var convertMutable: NSMutableString!
func showSendMailErrorAlert()
{
let sendMailErrorAlert = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert)
self.presentViewController(sendMailErrorAlert, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?)
{
controller.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func sendMailButtonTapped(sender: AnyObject){
print("Email Tapped")
convertMutable = NSMutableString();
for item in shoppingList
{
convertMutable.appendFormat("%@\r", item.name, item.quantity)
}
print("NSMutableString: \(convertMutable)")
let data = convertMutable.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
if let d = data {
print("NSData: \(d)")
}
func configuredMailComposeViewController() -> MFMailComposeViewController{
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["mh@derivan.com.au"])
mailComposerVC.setSubject("From the Orders App")
mailComposerVC.setMessageBody(String (items), isHTML: false)
mailComposerVC.addAttachmentData(data!, mimeType: "text/csv", fileName: "Order.csv")
return mailComposerVC
}
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail()
{
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
}
else
{
self.showSendMailErrorAlert()
}
}
let CellIdentifier = "Cell Identifier"
var items = [Item]() {
didSet {
buildShoppingList()
}
}
var shoppingList = [Item]() {
didSet {
tableView.reloadData()
//print (items)
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Order List"
loadItems()
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ShoppingListViewController.updateShoppingList(_:)), name: "ShoppingListDidChangeNotification", object: nil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shoppingList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath)
let item = shoppingList[indexPath.row]
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = String(format: "%.0f", item.quantity)
print (item.name, item.quantity)
return cell
}
func updateShoppingList(notification: NSNotification) {
loadItems()
}
func buildShoppingList() {
shoppingList = items.filter({ (item) -> Bool in
return item.inShoppingList
})
}
private func loadItems() {
if let filePath = pathForItems() where NSFileManager.defaultManager().fileExistsAtPath(filePath) {
if let archivedItems = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? [Item] {
items = archivedItems
}
}
}
private func pathForItems() -> String? {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
if let documents = paths.first, let documentsURL = NSURL(string: documents) {
return documentsURL.URLByAppendingPathComponent("items").path
}
return nil
}
}
答案 0 :(得分:0)
尝试下面的代码它可能有助于生成csv字符串文件
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setSubject("My app Data")
mailComposerVC.setMessageBody("my app doc csv", isHTML: false)
let csvStringData = generateStringForCSV()
let data = csvStringData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
mailComposerVC.addAttachmentData(data!, mimeType: "text/csv", fileName: fileName)
return mailComposerVC
}
func generateStringForCSV (currentSessionData:[String:String]) -> NSMutableString {
let delimiter = ","
let stringData:NSMutableString = NSMutableString()
let currentSessionData = sensorHeader + sensorsData
for data in currentSessionData {
stringData.appendString(data.0)
stringData.appendString(delimiter)
stringData.appendString(data.1)
stringData.appendString("\n")
}
return stringData
}
答案 1 :(得分:0)
感谢您的深思熟虑的答案,我已经设法在stackoverflow的帮助下解决了一些问题,现在已经使用以下代码成功附加了包含来自UITableView的item.name对象的CSV。
@IBAction func sendMailButtonTapped(sender: AnyObject){
print("Email Tapped")
convertMutable = NSMutableString();
for item in shoppingList
{
convertMutable.appendFormat("%@\r", item.name, item.quantity)
}
print("NSMutableString: \(convertMutable)")
let data = convertMutable.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
if let d = data {
print("NSData: \(d)")
}
func configuredMailComposeViewController() -> MFMailComposeViewController{
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["mh@derivan.com.au"])
mailComposerVC.setSubject("From the Orders App")
mailComposerVC.setMessageBody(String (items), isHTML: false)
mailComposerVC.addAttachmentData(data!, mimeType: "text/csv", fileName: "Order.csv")
return mailComposerVC
}
我是如此接近它是可笑的,但我无法处理收到的订单没有订单数量。 我现在坚持的问题是,如何将我的item.quantity对象与其item.name对象一起放入csv?
当我打印(item.name,item.quantity)时,我将它们放在输出中,但是将它们加在一起,同时转换为NSData我只能在我的csv中获取item.name。 我还将我的初始帖子中的代码更新到了我现在的位置。