Skip to content

Instantly share code, notes, and snippets.

@colinfwren
Last active January 10, 2025 22:39
Show Gist options
  • Save colinfwren/cd5df9477e39089c48dfee43ca79536a to your computer and use it in GitHub Desktop.
Save colinfwren/cd5df9477e39089c48dfee43ca79536a to your computer and use it in GitHub Desktop.
Data Export with Share Sheet
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@State private var sharingExport: Bool = false
@State private var exportUrl: URL?
var body: some View {
Button("Export your data") {
exportData()
}
.sheet(isPresented: $sharingExport) {
if let exportData = exportUrl {
ShareSheet(showing: $sharingExport, sharing: [exportData])
} else {
Text("Export being processed")
}
}
}
func getMarkdown(records: [Record]) -> String {
var markdown: String = "# Data Export\n\n"
for record in records {
exportData += "## Header\n\(record.somePropertyToInclude)\n"
}
return markdown
}
func dataExportUrl() {
let descriptor = FetchDescriptor<Record>()
let fetchedRecords = try? modelContext.fetch(descriptor)
if let records = fetchedRecords {
let markdown = getMarkdown(records)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let url = FileManager.default.temporaryDirectory.appendingPathComponent("export-\(dateFormatter.string(from: Date.now))").appendingPathExtension("md")
try? markdown.write(to: url, atomically: true, encoding: .utf8)
exportUrl = url
sharingExport = true
} else {
// something when there's no records
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment