NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Create and Export .txt File from CoreData FetchRequest in SwiftUI

Forums > SwiftUI

Hello everyone, I am asking myself and you whats the easiest way to create a .txt File from a CoreData FetchRequest in SwiftUI.

The File should have a structure like:

00:00:10 Baby prepares to rock 00:00:30 Baby rocks the house

Normaly I would do it like this:

ForEach(fetchRequest.wrappedValue, id: .self) { diary in VStack { HStack { Text(diary.time ?? "Error") } HStack { Text(diary.action ?? "Error") } } }

Of course thats code for a SwiftUI View, but I have no Idea how to deal with the result of a Fetch Request from CoreData to create a File and export it...


FetchRequest from SwiftUI is not made for this. You should use the standard Core Data fetch request to fetch all records outside the view and the use something like a for loop or map function to create an array of String. This can then be written to a file.


@nemecek-filip thanks for your answer. I would really appreciate, if you could share an example of such function or give me a link to a resource where I can find more about it, because I couldn't find something :/


You can create fetch requests like this:

@nonobjc public class func fetchRequest() -> NSFetchRequest<Commit> {
    return NSFetchRequest<Commit>(entityName: "Commit")

Where "Commit" will be replaced with the name of your class. Then you can use your managed object context to execute the fetch method to get all the instances. This HWS tutorial shows how to fetch the commits from above example -

I don't know how your Core Data setup looks like, but you should have access to the managed object context regardless and that will let you do the fetch.

If you are interested in how to do this in a background to possibly not block UI, I have post on my blog about setting up Core Data which includes example how to use background context -


Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Ever ask for help and your reviewer immediately notices issues you missed? Fernando Olivares is a 10-year veteran from Big Nerd Ranch and Lambda School who can help hone your app building skills, and he's just launched a new book that does just that – use the code "hacking" to save $5!

Buy the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

Not logged in

Log in

Link copied to your pasteboard.