UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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...

2      

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.

3      

@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 :/

2      

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 - https://www.hackingwithswift.com/read/38/5/loading-core-data-objects-using-nsfetchrequest-and-nssortdescriptor

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 - https://nemecek.be/blog/41/my-approach-to-setting-up-core-data-stack

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.