Data Management & Optimization

Apr 4 2025 · Swift 5.10, iOS 17.0, Xcode 15.4

Lesson 02: Data Transformation & Migration

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Demo

In this demo, you’ll update TheMet app to migrate the query storage away from App Storage and instead use Swift Data.

import Foundation
import SwiftData

@Model
class MetQuery {
  var query: String

  init(query: String) {
    self.query = query
  }
}
import SwiftUI
import SwiftData

@main
struct TheMetApp: App {
  var body: some Scene {
    WindowGroup {
      MetView().modelContainer(for: MetQuery.self)
    }
  }
}
@Environment(\.modelContext) private var modelContext

@Query private var lastMetQueries: [MetQuery]

@State private var currentMetQuery = ""

//@AppStorage("lastquery") private var lastQuery = "rhino"
Text("You searched for '\(currentMetQuery)'")
  .padding(5)
  .background(Color.metForeground)
  .cornerRadius(10)
Button("Search the Met") {
  modelContext.insert(MetQuery(query: currentMetQuery))
  showQueryField = true
}
.alert(
  "Search the Met",
  isPresented: $showQueryField,
  actions: {
    TextField("Search the Met", text: $currentMetQuery)
    Button("Search") {
      fetchObjectsTask?.cancel()
      fetchObjectsTask = Task {
        do {
          store.objects = []
          try await store.fetchObjects(for: currentMetQuery)
        } catch {}
      }
    }
})
.task {
  do {
    try await store.fetchObjects(for: currentMetQuery)
  } catch {}
}
.onAppear {
  currentMetQuery = lastMetQueries.last?.query ?? "rhino"
}
@State private var isShowingQueryHistory = false
Button("Show History Query") {
  isShowingQueryHistory = true
}
.sheet(isPresented: $isShowingQueryHistory) {
  LastQueriesView()
}
import SwiftUI
import SwiftData

struct LastQueriesView: View {
  @Environment(\.dismiss) var dismiss

  @Query private var lastMetQueries: [MetQuery]
}
var body: some View {
  NavigationStack {
    VStack {
      List(lastMetQueries, id: \.id) { query in
        Text(query.query)
      }
      .navigationTitle("Query History")
      .toolbar {
        Button("Close") {
          dismiss()
        }
      }
    }
  }
}
@AppStorage("lastquery") private var lastQuery = ""
See forum comments
Cinema mode Download course materials from Github
Previous: Data Transformation & Migration Next: Conclusion