This is a short way to do whatever you want - you pass in an array of managed objects and a string that is the name of the CSV file. The method writes the CSV to a file. I believe that you already have most of this code, what is missing is the last two lines, which simply write the line to a new file in the Documents directory.
func writeCoreDataObjectToCSV(objects: [NSManagedObject], named: String) -> String { guard objects.count > 0 else { return } let firstObject = objects[0] let attribs = Array(firstObject.entity.attributesByName.keys) let csvHeaderString = (attribs.reduce("",combine: {($0 as String) + "," + $1 }) as NSString).substringFromIndex(1) + "\n" let csvArray = objects.map({object in (attribs.map({(object.valueForKey($0) ?? "NIL").description}).reduce("",combine: {$0 + "," + $1}) as NSString).substringFromIndex(1) + "\n" }) let csvString = csvArray.reduce("", combine: +) return csvHeaderString+csvString }
Now, somewhere else in the code, you need to create an NSData from this line and add it to the mail composer:
let csvString = ..... let data = csvString.dataUsingEncoding(NSUTF8StringEncoding) let composer = MFMailComposeViewController() composer.addAttachmentData(attachment: data, mimeType mimeType: "text/csv", fileName filename: "mydata.csv")
Then make the usual material with the composer (set the body, theme, etc.) and present it to the user!
EDIT:
Edited the answer to better answer the question.
source share