SwiftData

RSS for tag

SwiftData is an all-new framework for managing data within your apps. Models are described using regular Swift code, without the need for custom editors.

Posts under SwiftData tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

What's the best way to support Genmoji with SwiftUI?
I want to support Genmoji input in my SwiftUI TextField or TextEditor, but looking around, it seems there's no SwiftUI only way to do it? If none, it's kind of disappointing that they're saying SwiftUI is the path forward, but not updating it with support for new technologies. Going back, does this mean we can only support Genmoji through UITextField and UIViewRepresentable? or there more direct options? Btw, I'm also using SwiftData for storage.
0
0
13
36m
SwiftData: Default value for added property
Let's say I have a model like this: @Model final class DataModel { var firstProperty: String = "" } Later on I create a new property as such: @Model final class DataModel { enum DataEnum { case dataCase } var firstProperty: String = "" var secondProperty: DataEnum? = .dataCase } My expectation is for the data that is already stored, the secondProperty would be added with a default value of .dataCase. However, it's being set to nil instead. I could have sworn it would set to the default value given to it. Has that changed, or has it always been this way? Does this require a migration plan?
0
0
45
6h
Sync SwiftData via CloudKit on App Start
I have an app that uses SwiftData with CloudKit to synchronize data across a users devices. I'm able to replicate data created on one device on another and when removing data, it is also removed on the other device. So, I know that SwiftData and CloudKit are configured correctly. What I'd like to do though, is to ensure that if a user installs the app on an additional device, that the data is synchronized upon app start. When testing my app on a third device, via TestFlight, there was no data in the app upon launch even though all three devices are using the same Apple account (e.g. Apple ID). What is the best way to achieve this?
2
1
58
10h
SiftData with CloudKit testing
I'm trying to add Cloud Kit integration to SwiftData app (that is already in the App Store, btw). When the app is installed on devices that are directly connected to Xcode, it works (a bit slow, but pretty well). But when the app is distributed to Testflight internal testers, the synchronization doesn't happen at all. So, is this situation normal and how can I test apps with iCloud integration properly?
0
0
76
1d
SwiftUI Color Issue
I have ran into an issue that is illustrated by the code in the following GitHub repository. https://github.com/dougholland/ColorTest When a SwiftUI color originates from the ColorPicker it can be persisted correctly and renders the same as the original color. When the color originates from the MapFeature.backgroundColor, it is always rendered with the light appearance version of the color and not the dark appearance version. The readme in the GitHub repo has screenshots that show this. Any assistance would be greatly appreciated as this is affecting an app that is in development and I'd like to resolve this before the app is released. If this is caused by a framework bug, any possible workaround would be greatly appreciated also. I suspect it maybe a framework issue, possibly with some code related to the MapFeature.backgroundColor, because the issue does not occur when the color originates from the ColorPicker.
0
1
87
2d
DocumentGroup with SwiftData BUG!!!!! (modelContext cannot save and querry)
This is a critical bug with Document-Based Apps (SwiftData). If you download the WWDC 2023 sample code for"Building a document-based app using SwiftData" , open it in Xcode 16.1, and run it on an iOS 18+ simulator, you'll encounter a major issue. When you exit a document and reopen it, you'll find that the changes you just made were not saved. iOS 18 has effectively rendered last year's WWDC 2023 sample code obsolete! Has anyone managed to successfully save data in a Document-Based App using SwiftData?
0
0
99
2d
MacOS CloudKit production environment is not working properly
My macOS app is developed using SwfitUI, SwiftData, and CloudKit. In the development environment, CloudKit works well. Locally added models can be quickly viewed in the CloudKit Console. macOS app and iOS app with the same BundleID can also synchronize data normally when developing locally. However, in the production environment, the macOS app cannot synchronize data with iCloud. But iOS app can. The models added in the production environment are only saved locally and cannot be viewed in CloudKit Console Production. I am sure I have configured correctly, container schema changes to deploy to the Production environment. I think there may be a problem with CloudKit in macOS. Please help troubleshoot the problem. I can provide you with any information you need. var body: some Scene { WindowGroup { MainView() .frame(minWidth: 640, minHeight: 480) .environment(mainViewModel) } .modelContainer(for: [NoteRecord.self]) } I didn't do anything special. I didn’t do anything special. I just used SwiftData hosted by CloudKit.
1
0
84
17h
Getting a crash for SwiftData that only happens on iPhone 16 pro
I'm getting a crash in SwiftData but only on one specific device (iPhone 16 pro running 18.2 22C5131e) and not on an ipad or simulator I cant troubleshoot this crash and its quite frustrating, all I am getting is @Query(sort: \Todo.timestamp, order: .reverse) private var todos: [Todo] ForEach(todos.filter { !$0.completed }) { item in // <---crash TodoListView() } and the error is Thread 1: signal SIGABRT An abort signal terminated the process. Such crashes often happen because of an uncaught exception or unrecoverable error or calling the abort() function. and _SwiftData_SwiftUI.Query.wrappedValue.getter : τ_0_1 -> 0x105b98b58 <+160>: ldur x8, [x29, #-0x40] 0x105b98b5c <+164>: ldur x0, [x29, #-0x38] 0x105b98b60 <+168>: ldur x1, [x29, #-0x30] 0x105b98b64 <+172>: ldur x9, [x29, #-0x20] 0x105b98b68 <+176>: stur x9, [x29, #-0x28] 0x105b98b6c <+180>: ldr x8, [x8, #0x8] 0x105b98b70 <+184>: blr x8 0x105b98b74 <+188>: ldur x0, [x29, #-0x28] 0x105b98b78 <+192>: sub sp, x29, #0x10 0x105b98b7c <+196>: ldp x29, x30, [sp, #0x10] 0x105b98b80 <+200>: ldp x20, x19, [sp], #0x20 0x105b98b84 <+204>: ret How do I fix this?
0
0
98
4d
SwiftData migration plan in app and widget
I have an app and widget that share access to a SwiftData container using App Groups. I have implemented a SwiftData migration plan, but I am unsure whether I should allow the widget to perform the migration (in addition to the app). I am concerned about two possible issues: If the app and widget are run at approximately the same time (e.g. the user taps Open after doing a manual update in the App Store), then both the app and widget might try to perform the migration at the same time, which could lead to race conditions / data corruption. If the widget is first to run but the widget gets suspended for some reasons (e.g., iOS decides it's using too many resources), then the migration might be suspended leaving the database in an corrupted state. To me, it feels like the safest option is to only allow the app itself to perform the migration – this will ensure that the migration can only happen once in a safe state. However, this will lead to problems for the widget. For example, if the user does not open the app for several days after an automatic update, the widget will be in a broken state, since it will not be able to open the container until it has been migrated by the app. Possible solutions I'm considering: Allow both the app and widget to perform the migration and cross my fingers. (Ignore Issue 1 and Issue 2) Implement some kind of UserDefaults flag that is set to true during migration, so that the app and widget will avoid performing the migration concurrently. (Solves Issue 1 but not Issue 2) Only perform the migration in the app, and then add code to the widget to detect which container version the widget has access to, so that the widget can continue to work with a v1 container until the app eventually updates it to a v2 container. (Solves Issue 1 and Issue 2, but leads to very convoluted code – especially over time) Things I'm unsure about: Will iOS continue to use v1 of the widget until the app is opened for the first time, at which point v2 of the widget is installed? Or does iOS immediately update the widget to v2 on update? Does iOS immediately refresh the widget timeline on update? Does SwiftData already have some logic to avoid migrations being performed twice, even from different threads? If so, how does it respond if one process tries to access a container while another process is performing a migration? Does anyone have any recommendations about how to handle these possible issues? What are best practices? Cheers!
0
1
92
6d
SwiftData: Failed to decode a composite attribute
I changed an enum value from this: enum Kind: String, Codable, CaseIterable { case credit } to this: enum Kind: String, Codable, CaseIterable { case credit = "Credit" } And now it fails to load the data. This is inside of a SwiftData model. I get why the error is occurring, but is there a way to resolve this issue without having to revert back or delete the data? Error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot initialize Kind from invalid String value credit", underlyingError: nil))
3
0
161
6d
SwiftData Master Details
I want to create master details relationship between patient and vitals signs so which of option codes below are better performance wise ? Option one is master - details done manually .. option 1 @Model class TestResult { @Attribute(.primaryKey) var id: UUID var patientID: UUID Option 2 @Model final class Vital { var patient: Patient?
0
0
94
1w
custom EnvironmentKey lookup causes compiler error
I receive the following compiler error: Cannot infer key path from context; consider explicitly specifying a root type when I attempt an @Environment(\.foodRepository) lookup in a descendant View. Here's the setup in my App class: import SwiftUI import SwiftData @main struct BulkCutApp: App { private var foodRepository: FoodRepository = /* some code*/ var body: some Scene { WindowGroup { ContentView() .foodRepository(foodRepository) } } } extension View { func foodRepository(_ customValue: FoodRepository) -> some View { environment(\.foodRepository, customValue) } } extension EnvironmentValues { var foodRepository: FoodRepository { get { self[FoodRepositoryKey.self] } set { self[FoodRepositoryKey.self] = newValue } } } struct FoodRepositoryKey: EnvironmentKey { static var defaultValue: FoodRepository = FoodRepository(food:[]) } Nothing special in FoodRepository: @Observable class FoodRepository { var food: [Food] // more code }
0
0
67
1w
Store SwiftUI Color in SwiftData
I have an app that needs to store a SwiftUI Color within SwiftData and I was wondering if anyone had found a way to do so easily and accurately. I'd prefer not to have to store the Color components (e.g. RGB values) and would ideally like to have a single variable in the @Model that stores the Color. I had considered using an extension to the Color type to create a HEX encoded String of the Color and an initializer that creates a Color from the HEX encoded String. Unfortunately, doing so proved not to be accurate due data loss when converting component values to integers. When testing this in Photoshop, the original color #FBAA1D became #FFAB00. Is there a way to accurately store the Color in SwiftData, possibly using a binary conversion to Data or somehow storing the Color.Resolved, which itself does not appear to be compatible with SwiftData. Any thoughts on how to best store the Color accurately within SwiftData would be greatly appreciated.
2
0
162
1w
SwiftUI not observing SwiftData changes
I have an app with the following model: @Model class TaskList { @Attribute(.unique) var name: String // Relationships var parentList: TaskList? @Relationship(deleteRule: .cascade, inverse: \TaskList.parentList) var taskLists: [TaskList]? init(name: String, parentTaskList: TaskList? = nil) { self.name = name self.parentList = parentTaskList self.taskLists = [] } } If I run the following test, I get the expected results - Parent has it's taskLists array updated to include the Child list created. I don't explicitly add the child to the parent array - the parentList relationship property on the child causes SwiftData to automatically perform the append into the parent array: @Test("TaskList with children with independent saves are in the database") func test_savingRootTaskIndependentOfChildren_SavesAllTaskLists() async throws { let modelContext = TestHelperUtility.createModelContext(useInMemory: false) let parentList = TaskList(name: "Parent") modelContext.insert(parentList) try modelContext.save() let childList = TaskList(name: "Child") childList.parentList = parentList modelContext.insert(childList) try modelContext.save() let fetchedResults = try modelContext.fetch(FetchDescriptor<TaskList>()) let fetchedParent = fetchedResults.first(where: { $0.name == "Parent"}) let fetchedChild = fetchedResults.first(where: { $0.name == "Child" }) #expect(fetchedResults.count == 2) #expect(fetchedParent?.taskLists.count == 1) #expect(fetchedChild?.parentList?.name == "Parent") #expect(fetchedChild?.parentList?.taskLists.count == 1) } I have a subsequent test that deletes the child and shows the parent array being updated accordingly. With this context in mind, I'm not seeing these relationship updates being observed within SwiftUI. This is an app that reproduces the issue. In this example, I am trying to move "Finance" from under the "Work" parent and into the "Home" list. I have a List that loops through a @Query var taskList: [TaskList] array. It creates a series of children views and passes the current TaskList element down into the view as a binding. When I perform the operation below the "Finance" element is removed from the "Work" item's taskLists array automatically and the view updates to show the removal within the List. In addition to that, the "Home" item also shows "Finance" within it's taskLists array - showing me that SwiftData is acting how it is supposed to - removed the record from one array and added it to the other. The View does not reflect this however. While the view does update and show "Finance" being removed from the "Work" list, it does not show the item being added to the "Home" list. If I kill the app and relaunch I can then see the "Finance" list within the "Home" list. From looking at the data in the debugger and in the database, I've confirmed that SwiftData is working as intended. SwiftUI however does not seem to observe the change. ToolbarItem { Button("Save") { list.name = viewModel.name list.parentList = viewModel.parentTaskList try! modelContext.save() dismiss() } } To troubleshoot this, I modified the above code so that I explicitly add the "Finance" list to the "Home" items taskLists array. ToolbarItem { Button("Save") { list.name = viewModel.name list.parentList = viewModel.parentTaskList if let newParent = viewModel.parentTaskList { // MARK: Bug - This resolves relationship not being reflected in the View newParent.taskLists?.append(list) } try! modelContext.save() dismiss() } } Why does my explicit append call solve for this? My original approach (not manually updating the arrays) works fine in every unit/integration test I run but I can't get SwiftUI to observe the array changes. Even more strange is that when I look at viewModel.parentTaskList.taskLists in this context, I can see that the list item already exists in it. So my code effectively tries to add it a second time, which SwiftData is smart enough to prevent from happening. When I do this though, SwiftUI observes a change in the array and the UI reflects the desired state. In addition to this, if I replace my custom list rows with an OutlineGroup this issue doesn't manifest itself. SwiftUI stays updated to match SwiftData when I remove my explicit array addition. I don't understand why my views, which is passing the TaskList all the way down the stack via Bindable is not updating while an OutlineGroup does. I have a complete reproducible ContentView file that demonstrates this as a Gist. I tried to provide the source here but it was to much for the post. One other anecdote. When I navigate to the TaskListEditorScreen and open the TaskListPickerScreen I get the following series of errors: error: the replacement path doesn't exist: "/var/folders/07/3px_03md30v9n105yh3rqzvw0000gn/T/swift-generated-sources/@_swiftmacro_09SwiftDataA22UIChangeDetectionIssue20TaskListPickerScreenV9taskLists33_A40669FFFCF66BB4EEA5302BB5ED59CELL5QueryfMa.swift" I saw another post regarding these and I'm wondering if my issue is related to this. So my question is, do I need to handle observation of SwiftData models containing arrays differently in my custom views? Why do bindings not observe changes made by SwiftData but they observe changes made explicitly by me?
0
0
151
1w
Getting error "Failed user key sync" when trying to connect to CloudKit after Xcode 16.1 update / iOS 18.1
Hey there, I’m feeling pretty desperate at this point, as my most recent update to Xcode 16.1 and the new 18.1 simulators has basically made it impossible for me to work on my apps. The same app and same code run fine in the 18.0 simulators with the same iCloud account logged in. I’ve tried multiple simulators with the same results, even on different computers. I’ve also tried logging in repeatedly without any luck. The CloudKit database logs don’t show any errors or suspicious entries. Reinstalling the app on the simulator doesn't help either. Whenever I launch the application in Xcode, I'm getting: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1240): <NSCloudKitMirroringDelegate: 0x600003d213b0>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x103f124e0> (URL: file:///Users/kerstenbroich/Library/Developer/CoreSimulator/Devices/57BC78CE-DB2A-4AC0-9D7A-43C386305F56/data/Containers/Data/Application/EFDE9B05-0584-47C5-80AE-F2FF5994860C/Library/Application%20Support/Model.sqlite) <CKError 0x600000d3dfe0: "Partial Failure" (2/1011); "Failed to modify some record zones"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x600000d7c090: "Internal Error" (1/5000); "Failed user key sync"> }> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:](2310): <NSCloudKitMirroringDelegate: 0x600003d213b0> - Attempting recovery from error: <CKError 0x600000d3dfe0: "Partial Failure" (2/1011); "Failed to modify some record zones"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x600000d7c090: "Internal Error" (1/5000); "Failed user key sync"> }> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:]_block_invoke(2773): <NSCloudKitMirroringDelegate: 0x600003d213b0>: Found unknown error as part of a partial failure: <CKError 0x600000d7c090: "Internal Error" (1/5000); "Failed user key sync"> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:](2820): <NSCloudKitMirroringDelegate: 0x600003d213b0>: Error recovery failed because the following fatal errors were found: { "<CKRecordZoneID: 0x600000d62340; zoneName=com.apple.coredata.cloudkit.zone, ownerName=__defaultOwner__>" = "<CKError 0x600000d7c090: \"Internal Error\" (1/5000); \"Failed user key sync\">"; } Any help/ideas would be much appreciated, because I have no clue what to try next. Thanks a lot!
3
3
222
2d
SwiftData error "Thread 1: Fatal error: Composite Coder only supports Keyed Container"
I'm using SwiftData to store data in my app and I recently had to store both image data and colors. I have therefore added two variables to my model, one of type Data? and the other of type Color.Resolved? If both are set to nil then I can call context.save() without any error but when providing a value of type Color.Resolved, the following error message occurs: Thread 1: Fatal error: Composite Coder only supports Keyed Container. Any guidance on how to solve this and what needs to be done to store image data and colors with SwiftData?
1
0
125
1w
[SwiftData] How to use @Query to get the first 7 elements in the list
Maybe I didn't find the relevant instructions. In my code, I only want to get the first 7 elements. At present, my code is as follows: @Query(sort:\Record.date, order: .reverse) private var records:[Record] But I wonder if once the number of records is large, will it affect the efficiency? In View, it is enough for me to count the first 7 elements in records. What should I do?
1
0
165
1w