Skip to content

Instantly share code, notes, and snippets.

@aindong
Last active January 8, 2023 20:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aindong/b1a61d0f8e792855705d941ccc60cda8 to your computer and use it in GitHub Desktop.
Save aindong/b1a61d0f8e792855705d941ccc60cda8 to your computer and use it in GitHub Desktop.
Export Core Data into CSV in Swift 3
func createExportString() -> String {
var name : String?
var age : String?
var mobile : String?
var email : String?
var promo_crayola_bunding : Int16?
var promo_zip_it : Int16?
var promo_none : Int16?
var created : NSDate? = NSDate()
var export : String = NSLocalizedString("Name, Age, Mobile, Email, Crayola Bunding, Zip It, None, Created Date \n", comment: "")
for (index, census) in self.fetchAllCensus().enumerated() {
name = census.name
age = census.age
mobile = census.mobile
email = census.email
promo_crayola_bunding = census.promo_crayola_building
promo_zip_it = census.promo_zip_it
promo_none = census.promo_none
created = census.created
let promoCrayolaBundingString = "\(promo_crayola_bunding)"
let promoZipItString = "\(promo_zip_it)"
let promoNoneString = "\(promo_none)"
let createdDateString = "\(created!)"
export += name + "," + age + "," + mobile + "," + email + "%,"
+ promoCrayolaBundingString + "," + promoZipItString + "," + promoNoneString + "," + createdDateString + "\n"
}
return export
}
func saveAndExport(exportString: String) {
let exportFilePath = NSTemporaryDirectory() + "export.csv"
let exportFileURL = NSURL(fileURLWithPath: exportFilePath)
FileManager.defaultManager.createFileAtPath(exportFilePath, contents: NSData() as Data, attributes: nil)
var fileHandleError: NSError? = nil
var fileHandle: FileHandle? = nil
do {
fileHandle = try FileHandle(forWritingToURL: exportFileURL)
} catch {
print("Error with fileHandle")
}
if fileHandle != nil {
fileHandle!.seekToEndOfFile()
let csvData = exportString.data(using: String.Encoding.utf8, allowLossyConversion: false)
fileHandle!.writeData(csvData!)
fileHandle!.closeFile()
let firstActivityItem = NSURL(fileURLWithPath: exportFilePath)
let activityViewController : UIActivityViewController = UIActivityViewController(
activityItems: [firstActivityItem], applicationActivities: nil)
activityViewController.excludedActivityTypes = [
UIActivityType.assignToContact,
UIActivityType.saveToCameraRoll,
UIActivityType.postToFlickr,
UIActivityType.postToVimeo,
UIActivityType.postToTencentWeibo
]
self.present(activityViewController, animated: true, completion: nil)
}
}
@omarojo
Copy link

omarojo commented Jul 26, 2018

Very nice... quick question. How big/long can the 'exportString' be ? Can it hold infinite data? like 100000000 records ?

@Asheshp23
Copy link

This will fail if any field contains "\n". ("name" = "A\nB\nC")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment