Hi all,
I am starting using the new amazing SwiftData and I really like it!
I have a question regarding how to pass the filter predicate from the parent view.
In my app I have a simple case where I have a package that contains multiple items.
When I package is selected a view is pushed with the list of items in that package.
The Items view has a query as following:
struct ScoreListView: View {
[.....]
@Query(filter: #Predicate<SWDItem> { item in
item.package?.id == selectedPackage.id
} ,sort: \.timestamp) var items: [SWDItem]
[.....]
var body: some View {
[...]
}
The problem is that selectedPackage is not "yet" available when defining the @Query and I have the classic error "Cannot use instance member 'selectedPackage' within property initializer; property initializers run before 'self' is available".
How can I structure the code to have the selected package available when the @Query is defined?
Thank you a lot
Post
Replies
Boosts
Views
Activity
Hi All,
I am using SwiftData for my new app, that is going to have also Extension and Apple Watch app companion.
At the moment I am configuring the iOS/iPadOS app as following:
My Persistency Library
public let fullSchema: Schema = Schema([
SWDItem.self,
SWDPackage.self
])
public func makeContainer() -> ModelContainer {
let configuration = ModelConfiguration(
"SWDMyApp",
schema: fullSchema,
sharedAppContainerIdentifier: "my.appgroup.id",
cloudKitContainerIdentifier: "iCloud.my.icloud.id")
return try! ModelContainer(for: fullSchema, configuration)
}
And at the start of the app there is the following configuration as described in SwiftData documentation:
iOS/iPad OS
@main
struct MyApp: App {
let container = SWDModelContainer().makeContainer()
[...]
var body: some Scene {
WindowGroup {
LaunchScreen()
}
.modelContainer(container)
}
I did the same thing both on the iOS/iPadOS code as well as in the AppleWatch app:
Apple Watch App
@main
struct MyAppWatch: App {
let container = SWDModelContainer().makeContainer()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(container)
}
}
The model configuration is defined in a Swift Package. Therefore the code to configure the model container is exactly the same.
The app works perfectly and can store data successfully. Data are persisted.
The Watch app does not see the data saved from the phone.
It launches without issues, but the items returned are 0.
I doubled checked that:
Both apps have the same appGroup ID setup
App group is enabled with the entitlement in both targets
The AppGroupID used in both apps is the one defined in sharedAppContainerIdentifier: "my.appgroup.id"
Are those 3 steps enough to share the SwiftData DB among targets (extensions/watch app/ ios...) or there is something I am missing here?
Thanks for your help in advance.
Dear all,
Since It is my first apple watch application I just realized that is not possible to use AppGroups to sync between devices and after I spent 5 days in debugging something impossible to do 🙁 ...
... I am now trying to sync between iPhone and AppleWatch using iCloud (CloudKit), SwiftData and the following code (on iOS 17 and Watch OS 10 - beta 3):
My Persistency Library
public let fullSchema: Schema = Schema([
SWDItem.self,
SWDPackage.self
])
public func makeContainer() -> ModelContainer {
let configuration = ModelConfiguration(
"SWDMyApp",
schema: fullSchema,
sharedAppContainerIdentifier: "my.appgroup.id",
cloudKitContainerIdentifier: "iCloud.my.icloud.id")
return try! ModelContainer(for: fullSchema, configuration)
}
And at the start of the app there is the following configuration as described in SwiftData documentation:
iOS/iPad OS
@main
struct MyApp: App {
let container = SWDModelContainer().makeContainer()
[...]
var body: some Scene {
WindowGroup {
LaunchScreen()
}
.modelContainer(container)
}
And the same for AppleWatch
Watch OS 10
@main
struct MyAppWatch: App {
let container = SWDModelContainer().makeContainer()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(container)
}
}
The model configuration is defined in a Swift Package. Therefore the code to configure the model container is exactly the same.
The app works perfectly and can store data successfully. Data are persisted.
The iCloud sync works between my iPad and my iPhone, BUT NOTHING ARRIVES TO APPLE WATCH.
The entitlements of the applewatch is the following:
Where iCloud container and AppGroup container match the iOS ones.
I am logged in with the same iCloud account in all devices
The watch is connected to WiFi
Why the SwiftData sync does not work on AppleWatch? What else can I check to make it work?
Thanks a lot in advance for your help
Hi all,
I am trying to render my SwiftUI views that uses SwiftData classes using sample data using the approach shown in the example code of wwdc2023-10196:
@MainActor #Preview {
TripsWidgetEntryView()
.modelContainer(PreviewSampleData.container)
}
Unfortunately this seems no longer valid.
Indeed I get this error:
I then tried to remove the @MainActor as suggested, but the error in then moved to another level:
What do you suggest to be the best approach to have back my preview working?
I am using Xcode Beta 4 - 15A5195m
Environment:
Xcode 15.3.0.
MacOS 14.4.1 (23E224)
Depl. Target: iOS 17.2
Supported Destinations: iPhone
Notes: Using SwiftData. Shared code in the Persistency library.
Hello everyone,
I am writing here after really trying everything I can to understand what is going on.
I have a widget bundle composed by two different widgets, defined as following:
import WidgetKit
import SwiftUI
import SwiftData
@main
struct MyWidgetBundle: WidgetBundle {
@WidgetBundleBuilder
var body: some Widget {
MyWidget()
MylMediumWidget()
}
}
They have 2 different providers (since they need different data).
The are then defined as following:
import SwiftUI
import WidgetKit
import Persistency
import SwiftData
struct MyMediumWidget: Widget {
let kind: String = "MyStatus"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: MyEntryProvider()) { entry in
MyMediumWidgetView(entry: entry)
.containerBackground(Color.Theme.background, for: .widget)
}
.supportedFamilies([.systemMedium, .systemLarge])
.configurationDisplayName("My Reminder Medium")
.description("Bla bla bla")
}
}
And
import WidgetKit
import SwiftUI
import Persistency
struct MyWidget: Widget {
let kind: String = "MyStatus"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: SmallEntryProvider()) { entry in
MyWidgetGroup(entry: entry)
.containerBackground(Color.Theme.background, for: .widget)
}
.supportedFamilies([.systemSmall, .accessoryCircular])
.configurationDisplayName("My Reminder Small")
.description("Bla bla 2")
}
}
struct ActiveMealWidgetGroup: View {
var entry: SmallEntryProvider.Entry
@Environment(\.widgetFamily) var family
var body: some View {
switch family {
case .systemSmall:
MySmallWidgetView(entry: entry)
case .accessoryCircular:
MyAcessoryCircularWidgetView(entry: entry)
default:
Text("Unsupported size")
}
}
}
Note: They belong to 1 single Widget Extension for iOS.
For some reason I have VERY strange behaviors in widgets with the following code.
Example:
When I insert the medium size, it is randomly removed from the home screen. For example, I add the small and the medium. After 3h, the medium is gone.
If I try to add the widgets in mac os (readying from phone, the app is only for iOS), only the small appears. No medium and large are shown.
If I try to compile the widget scheme selecting systemLarge in the xcode argument, I have an error saying: "Request widget family (systemLarge) is not supported by this widget kind (MyStatus)" UserInfo={NSLocalizedDescription=Request widget family (systemLarge) is not supported by this widget kind (MyStatus)}}
What is going on? Seems my widgets are really wrongly configured, but I can't see where the issue can be.
Hope someone can help me.
Best Regards
Hello everyone,
I am trying to train using CreateML Version 6.0 Beta (146.1), feature extractor Image Feature Print v2.
I am using 100K images for a total ~4GB on my M3 Max 48GB (MacOs 15.0 Beta (24A5279h))
The images seems to be correctly read and visualized in the Data Source section (no images with corrupted data seems to be there).
When I start the training it's all fine for the first 6k ~ 7k pictures, then I receive the following error:
Failed to create CVPixelBufferPool. Width = 0, Height = 0, Format = 0x00000000
It is the first time I am using it, so I don't really have so much of experience.
Could you help me to understand what could be the problem?
Thanks a lot
Hi All,
I am posting this to get some help on fetching Water intake data from Health Kit.
I have done (following a similar approach, and perfectly working) the fetch of the user weight, but for the water, somehow, I always receive back 0 samples.
I went to the Health App, added few entries (in different days) for the water intake, under the food sections.
Then, I use the following snippet to read the values, but I always have 0 values back.
What I am doing wrong?
let type = HKQuantityType(.dietaryWater)
let samplePredicate = HKSamplePredicate.sample(type: type, predicate: nil)
// Create the descriptor.
let descriptor = HKSampleQueryDescriptor(
predicates: [samplePredicate],
sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)])
let results = try await descriptor.result(for: hkHealthStore)
The results variable is always 0 elements.
What I am doing wrong?
PS: The permissions are checked and correctly given for this: HKQuantityType(.dietaryWater)
I updated today at Xcode 16 beta 6, and my app using SwiftData on iOS 18 (beta 6) is getting now this new error when saving the model in the modelContext.
I don't understand if it is a regression introduced in the beta 6 or if it is enforced something that previously wasn't.
It seems to be always referred to the ID property, for example:
SwiftData/ModelCoders.swift:1762: Fatal error: Passed nil for a non-optional keypath \MyModel.id
In this case (and in most of the cases in my models) the ID is defined as following
@Attribute(.unique)
public var id: UUID
I also tried to add the initialization inline, but didn't help
@Attribute(.unique)
public var id: UUID = .init()
I also tried to remove the @Attribute(.unique), didn't help as well.
Does any of you have the same issue?