Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i exactly export a csv file from iOS written in swift?

I am trying to export an cvs file.

With the following code i manage to get the file

let fileName = "sample.csv"//"sample.txt"        
    @IBAction func createFile(sender: AnyObject) {
            let path = tmpDir.stringByAppendingPathComponent(fileName)
            let contentsOfFile = "No,President Name,Wikipedia URL,Took office,Left office,Party,Home State\n1,George Washington,http://en.wikipedia.org/wiki/George_Washington,30/04/1789,4/03/1797,Independent,Virginia\n2,John Adams,http://en.wikipedia.org/wiki/John_Adams,4/03/1797,4/03/1801,Federalist,Massachusetts\n3,Thomas Jefferson,http://en.wikipedia.org/wiki/Thomas_Jefferson,4/03/1801,4/03/1809,Democratic-Republican,Virginia\n4,James Madison,http://en.wikipedia.org/wiki/James_Madison,4/03/1809,4/03/1817,Democratic-Republican,Virginia\n5,James Monroe,http://en.wikipedia.org/wiki/James_Monroe,4/03/1817,4/03/1825,Democratic-Republican,Virginia\n6,John Quincy Adams,http://en.wikipedia.org/wiki/John_Quincy_Adams,4/03/1825,4/03/1829,Democratic-Republican/National Republican,Massachusetts"
                //"Sample Text repacement for future cvs data"content to save

            // Write File

            do {
                try contentsOfFile.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
                print("File sample.txt created at tmp directory")
            } catch {

                print("Failed to create file")
                print("\(error)")
            }

        }

// Share button
    @IBAction func shareDoc(sender: AnyObject) {
        print("test share file")

         docController.UTI = "public.comma-separated-values-text"
            docController.delegate = self//delegate
            docController.name = "Export Data"
            docController.presentOptionsMenuFromBarButtonItem(sender as! UIBarButtonItem, animated: true)

        //}
    }

When i click the share file button in the simulator i see the following:

enter image description here

and with quick look it shows

enter image description here

So the next thing i did was testing with my iphone 5 and i tried to email sample.csv but i am only getting the message body and not the csv file???

  1. how can i actually email the .csv file?
  2. which export possibilities are there?
like image 655
alex Avatar asked Sep 15 '15 18:09

alex


2 Answers

In order to email the .csv file, you can do the following:

  1. Add this import to the top of the class. It allows you to use MFMailComposeViewController, which is a way to send emails.

    import MessageUI
    
  2. Generate your data, a sample I have done is:

    // Creating a string.
    var mailString = NSMutableString()
    mailString.appendString("Column A, Column B\n")
    mailString.appendString("Row 1 Column A, Row 1 Column B\n")
    mailString.appendString("Row 2 Column A, Row 2 Column B\n")
    
    // Converting it to NSData.
    let data = mailString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    
    // Unwrapping the optional.
    if let content = data {           
        print("NSData: \(content)")
    }
    
  3. Generate the MFMailComposeViewController

    // Generating the email controller.
        func configuredMailComposeViewController() -> MFMailComposeViewController {
            let emailController = MFMailComposeViewController()
            emailController.mailComposeDelegate = self
            emailController.setSubject("CSV File")
            emailController.setMessageBody("", isHTML: false)
    
            // Attaching the .CSV file to the email.
            emailController.addAttachmentData(data!, mimeType: "text/csv", fileName: "Sample.csv")
    
            return emailController
        }
    
    // If the view controller can send the email.
    // This will show an email-style popup that allows you to enter
    // Who to send the email to, the subject, the cc's and the message.
    // As the .CSV is already attached, you can simply add an email 
    // and press send.
        let emailViewController = configuredMailComposeViewController()
        if MFMailComposeViewController.canSendMail() {
            self.presentViewController(emailViewController, animated: true, completion: nil)
        }
    

In your case, as you have already created the file, you can simply attach that directly by changing the line where the CSV is attached to the mail for:

    emailController.addAttachmentData(NSData(contentsOfFile: "YourFile")!, mimeType: "text/csv", fileName: "Sample.csv")

Answer based on: Attach csv to email xcode , Create CSV file in Swift and write to file

like image 121
Lucas Avatar answered Nov 09 '22 23:11

Lucas


Creating CSV file in Swift

class ViewController: UIViewController {

var taskArr = [Task]()
var task: Task!

override func viewDidLoad() {
    super.viewDidLoad()
    task = Task()
    for _ in 0..<5 {
        task.name = "Raj"
        task.date = "\(Date())"
        task.startTime = "Start \(Date())"
        task.endTime = "End \(Date())"
        taskArr.append(task!)
    }

    creatCSV()
}

// MARK: CSV file creating
    func creatCSV() -> Void {
        let fileName = "Tasks.csv"
        let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
        var csvText = "Date,Task Name,Time Started,Time Ended\n"

        for task in taskArr {
            let newLine = "\(task.date),\(task.name),\(task.startTime),\(task.endTime)\n"
            csvText.append(newLine)
        }

        do {
            try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
        } catch {
            print("Failed to create file")
            print("\(error)")
        }
        print(path ?? "not found")
    }
}

Task Model class

class Task: NSObject {
    var date: String = ""
    var name: String = ""
    var startTime: String = ""
    var endTime: String = ""
}

CSV output show as below format

enter image description here

like image 33
Raj Joshi Avatar answered Nov 10 '22 00:11

Raj Joshi