How to create a CSV file from Core Data (swift)

前端 未结 1 962
孤独总比滥情好
孤独总比滥情好 2021-02-03 14:56

I\'m building an app with core data (1 entity with 5 attributes) that display in a tableView. Now i would like to export this data to a CSV file (so i can send this file with m

相关标签:
1条回答
  • 2021-02-03 15:37

    This is a concise way of doing all you want - you pass array of managed objects and a string that is CSV's filename. The method writes your CSV to a file. I believe you already have most of this in your code, the thing that is lacking are last two lines that just write a string into a new file in "Documents" directory.

    func writeCoreDataObjectToCSV(objects: [NSManagedObject], named: String) -> String? {
        /* We assume that all objects are of the same type */
        guard objects.count > 0 else {
            return nil
        }
        let firstObject = objects[0]
        let attribs = Array<Any>(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 NSData from this string and add it to 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, do the usual stuff with the composer (set body, topic, etc) and present it to the user!

    EDIT:

    Edited the answer to better answer the question.

    0 讨论(0)
提交回复
热议问题