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

Invalid Swift Support
Hi, Can someone please help me with the below issue, I validated the app before distributing from Xcode, and it passed. but I received a mail from Apple Developer Relations saying there a problem, but I don't have any clue how to solve this problem. ITMS-90429: Invalid Swift Support - The files libswiftDarwin.dylib, libswiftDispatch.dylib, libswiftCoreGraphics.dylib, libswiftCoreFoundation.dylib, libswiftUIKit.dylib, libswiftMetal.dylib, libswiftCore.dylib, libswiftFoundation.dylib, libswiftQuartzCore.dylib, libswiftos.dylib, libswiftObjectiveC.dylib, libswiftCoreImage.dylib aren’t at the expected location /Payload/connectdots.app/Frameworks. Move the file to the expected location, rebuild your app using the current public (GM) version of Xcode, and resubmit it. I dont know where these dylibs are now and how to move them. Also I am using Xcode 15.3. what does it mean current public version of Xcode Thanks in Advance, Thirupathi.
0
0
35
19h
Why does my SwiftUI app crash when opened from an intent?
I'm encountering a crash in my SwiftUI app when it is opened via an AppIntent. The app runs perfectly when launched by tapping the app icon, but it crashes when opened from an intent. Here is a simplified version of my code: import AppIntents import SwiftData import SwiftUI @main struct GOGODemoApp: App { @State private var state: MyController = MyController() var body: some Scene { WindowGroup { MyView() //.environment(state) // ok } .environment(state) // failed to start app, crash with 'Dispatch queue: com.apple.main-thread' } } struct MyView: View { @Environment(MyController.self) var stateController var body: some View { Text("Hello") } } @Observable public class MyController { } struct OpenIntents: AppIntent { static var title: LocalizedStringResource = "OpenIntents" static var description = IntentDescription("Open App from intents.") static var openAppWhenRun: Bool = true @MainActor func perform() async throws -> some IntentResult { return .result() } } Observations: The app works fine when launched by tapping the app icon. The app crashes when opened via an AppIntent. The app works if I inject the environment in MyView instead of in WindowGroup. Question: Why does injecting the environment in WindowGroup cause the app to crash when opened from an intent, but works fine otherwise? What is the difference when injecting the environment directly in MyView?
0
0
55
2d
SwiftData rollback not updating the UI
I'm building a simple App using SwiftData. In my app a user can create, remove and edit posts. When editing, I want them to be able to hit "Save" to persist the changes or "Cancel" to discard the changes. The approach I'm using is to disable autosave and call modelContext.save() when saving and modelContext.rollback() when discarding the changes. So my modelContainer is defined as follows: WindowGroup { ContentView() .modelContainer(for: [Post.self], isAutosaveEnabled: false) } and I Save and Cancel like this: PostForm(post: post) .toolbar { ToolbarItemGroup(placement: .cancellationAction) { Button("Cancel") { if modelContext.hasChanges { modelContext.rollback() } dismiss() } } ToolbarItemGroup(placement: .confirmationAction) { Button("Save") { do { if modelContext.hasChanges { try modelContext.save() } } catch { fatalError("Failed to save post: \(error.localizedDescription)") } callback?() dismiss() } } } The issue I am facing is that after calling modelContext.rollback() my Posts aren't updating in the UI, they still show the changes. Restarting the app shows the Posts without the changes so I'm guessing that modelContext.rollback() is in fact discarding the changes and not persisting them in the Storage, the UI is the one that is not reacting to the change. Am I doing something wrong here? Is this approach correct?
0
0
87
3d
Xcode 16 Beta 3: "Cannot expand accessors on variable declared with 'let'"
Running into this new issue in beta 3. All of our immutable model attributes are now triggering swift compiler error from the title (tied to swift 6 - warning in swift 5). Neither warning or error show up on previous builds. Anyone else running into this? Hopefully not a limitation on swiftData that attributes must be mutable? filed as: FB14379932 (new in Xcode 16 beta3: "cannot expand accessors on variable declared with 'let'" in SwiftData Models)
3
0
145
2d
SwiftData Initial sync on MacOS is partial
Yesterday I bumped into a weird issue. I've got an application that was previously only available on iOS, however I'm now creating a version for MacOS. As I released the "working" application to TestFlight, a friend of mine told me that they don't see any of their data in the mac application. Thus, I started to investigate, and found out that on the Testflight version, the initial sync fails to sync data that didn't exist before the installation. However, in the debug version of the application (directly ran from XCode) the initial sync syncs all data, and after downloading the production version from TestFlight it works like a charm.
0
0
66
4d
Model Container Sendable Throwing Error in Swift 6
Hi all, I just wanted to ask how people were using ModelActor with the Swift 6 language mode enabled. My current implementation involves passing the ModelContainer to my ModelActor, which worked in Sonoma and previous betas of Sequoia, however in the current Beta 3, I get this error: "Sending 'self.modelContext.container' risks causing data races" I am a bit confused by this, as from what I understand, ModelContainer conforms to Sendable, so ideally this error should not be thrown. Is this a bug in Beta 3? Thanks in advance.
1
1
167
5d
ModelActors not persisting relationships in iOS 18 beta
I've already submitted this as a bug report to Apple, but I am posting here so others can save themselves some troubleshooting. This is submitted as FB14337982 with an attached complete Xcode project to replicate. In iOS 17 we use a ModelActor to download data which is saved as an Event, and then save it to SwiftData with a relationship to a Location. In iOS 18 22A5307d we are seeing that this code no longer persists the relationship to the Location, but still saves the Event. If we put a breakpoint in that ModelActor we see that the object graph is correct within the ModelActor stack trace at the time we call modelContext.save(). However, after saving, the relationship is missing from the default.store SQLite file, and of course from the app UI. Here is a toy example showing how inserting an Employee into a Company using a ModelActor gives unexpected results in iOS 18 22A5307d but works as expected in iOS 17. It appears that no relationships data survives being saved in a ModelActor.ModelContext. Also note there seems to be a return of the old bug that saving this data in the ModelActor does not update the @Query in the UI in iOS 18 but does so in iOS 17. Models @Model final class Employee { var uuid: UUID = UUID() @Relationship(deleteRule: .nullify) public var company: Company? /// For a concise display @Transient var name: String { self.uuid.uuidString.components(separatedBy: "-").first ?? "NIL" } init(company: Company?) { self.company = company } } @Model final class Company { var uuid: UUID = UUID() @Relationship(deleteRule: .cascade, inverse: \Employee.company) public var employees: [Employee]? = [] /// For a concise display @Transient var name: String { self.uuid.uuidString.components(separatedBy: "-").first ?? "NIL" } init() { } } ModelActor import OSLog private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SimpleModelActor") @ModelActor final actor SimpleModelActor { func addEmployeeTo(CompanyWithID companyID: PersistentIdentifier?) { guard let companyID, let company: Company = self[companyID, as: Company.self] else { logger.error("Could not get a company") return } let newEmployee = Employee(company: company) modelContext.insert(newEmployee) logger.notice("Created employee \(newEmployee.name) in Company \(newEmployee.company?.name ?? "NIL")") try! modelContext.save() } } ContentView import OSLog private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "View") struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var companies: [Company] @Query private var employees: [Employee] @State private var simpleModelActor: SimpleModelActor! var body: some View { ScrollView { LazyVStack { DisclosureGroup("Instructions") { Text(""" Instructions: 1. In iOS 17, tap Add in View. Observe that an employee is added with Company matching the shown company name. 2. In iOS 18 beta (22A5307d), tap Add in ModelActor. Note that the View does not update (bug 1). Note in the XCode console that an Employee was created with a relationship to a Company. 3. Open the default.store SQLite file and observe that the created Employee does not have a Company relationship (bug 2). The relationship was not saved. 4. Tap Add in View. The same code is now executed in a Button closure. Note in the XCode console again that an Employee was created with a relationship to a Company. The View now updates showing both the previously created Employee with NIL company, and the View-created employee with the expected company. """) .font(.footnote) } .padding() Section("**Companies**") { ForEach(companies) { company in Text(company.name) } } .padding(.bottom) Section("**Employees**") { ForEach(employees) { employee in Text("Employee \(employee.name) in company \(employee.company?.name ?? "NIL")") } } Button("Add in View") { let newEmployee = Employee(company: companies.first) modelContext.insert(newEmployee) logger.notice("Created employee \(newEmployee.name) in Company \(newEmployee.company?.name ?? "NIL")") try! modelContext.save() } .buttonStyle(.bordered) Button("Add in ModelActor") { Task { await simpleModelActor.addEmployeeTo(CompanyWithID: companies.first?.persistentModelID) } } .buttonStyle(.bordered) } } .onAppear { simpleModelActor = SimpleModelActor(modelContainer: modelContext.container) if companies.isEmpty { let newCompany = Company() modelContext.insert(newCompany) try! modelContext.save() } } } }
0
0
93
5d
Context.insert() but at index 0
Hello! I am an inexperienced programmer learning swiftUI and swiftData so apologies in advance if this answer can be found elsewhere. I want to display a list of recent transcriptions, stored in modelContainer, in reversed order. I attempted to do transcriptionsList.reversed() in a ForEach (which is in a swiftUI List), but .onDelete gets messed up as it is deleting the items as per the normal order. The question is, is there a way when using context.insert(), that I can specify to insert at index 0? Or is there a better way of resolving this? Thanks in advance! The code when pasted in here appears to not be formatted correctly so I didn't include code
2
0
79
5d
Non-Optional One-To-Many Relationship Missing Object In Array
I'm encountering an issue with a one-to-many relationship between two models using SwiftData. Here's a simple example of my models: @Model final class TVSeries { var title: String @Relationship(deleteRule: .cascade, inverse: \Episode.tvSeries) var episodes: [Episode] init(title: String, episodes: [Episode] = []) { self.title = title self.episodes = episodes } } @Model final class Episode { var title: String var tvSeries: TVSeries // <- Works fine when optional init(title: String, tvSeries: TVSeries) { self.title = title self.tvSeries = tvSeries } } After creating and saving a TVSeries instance with an associated Episode, fetching the TVSeries instance shows that the episodes array remains empty whereas the back-link to the TVSeries works as expected. Here's the relevant test case: struct SwiftDataTestingTests { @Test func testFullInit() async throws { // Configure SwiftData context let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: TVSeries.self, Episode.self, configurations: config) let context = ModelContext(container) context.autosaveEnabled = false // Create entries let tvSeries = TVSeries(title: "New Series") let episode = Episode(title: "Episode 1", tvSeries: tvSeries) context.insert(episode) try context.save() // Fetch tv series let tvSeriesDescriptor = FetchDescriptor<TVSeries>() let tvSeriesResult = try context.fetch(tvSeriesDescriptor) #expect(tvSeriesResult.count == 1) let fetchedTVSeries = try #require(tvSeriesResult.first) #expect(fetchedTVSeries.episodes.count == 1) // <- Expectation failed: (fetchedTVSeries.episodes.count → 0) == 1 // Fetch episodes let episodeDescriptor = FetchDescriptor<Episode>() let episodeResult = try context.fetch(episodeDescriptor) #expect(episodeResult.count == 1) let fetchedEpisode = try #require(episodeResult.first) #expect(fetchedEpisode.tvSeries.title == "New Series") } } Everything seems fine when I make the tvSeries attribute in the Episode model optional, but I would prefer to leave it explicit. I tested this on the latest XCode and XCode Beta versions running macOS Sonoma XCode Version: 15.4 (15F31d) XCode Beta Version: 16.0 beta 3 (16A5202i) MacOS Version: 14.5 (23F79) Any insights or suggestions on what might be causing this issue would be greatly appreciated. Thank you!
0
0
102
6d
SwiftData - error: Error: Persistent History (2) has to be truncated due to the following entities being removed: ( A )
I'm having trouble resolving the error. If I save data in view A and open view B, I get an error. If I open only view A, or only view B, there is no problem, but when I open a second view (A to B, B to A, etc.) I get an error. Attached is the code that reproduces the problem. We would appreciate your cooperation. No simulator is used. Xcode: Version 15.4 (15F31d) iPone11: 17.5.1 Thank you. Error error: Error: Persistent History (2) has to be truncated due to the following entities being removed: ( A ) warning: Warning: Dropping Indexes for Persistent History warning: Warning: Dropping Transactions prior to 2 for Persistent History warning: Warning: Dropping Changes prior to TransactionID 2 for Persistent History Code import SwiftUI import SwiftData @main struct issueApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: [A.self, B.self]) } } } import SwiftUI import SwiftData struct ContentView: View { @State var showAView: Bool = false @State var showBView: Bool = false var body: some View { VStack { Button("show A"){ showAView.toggle() } .sheet(isPresented: $showAView){ AView() } Button("show B"){ showBView.toggle() } .sheet(isPresented: $showBView){ BView() } } } } struct AView: View { @Environment(\.modelContext) var context @Query private var list: [A] let query = QueryData<A>() var body: some View { VStack { if list.count > 0 { VStack { List { ForEach(list, id: \.number){ item in VStack { Text(item.number) } } } Button("clear"){ try? context.delete(model: A.self) } } } else { Button("set"){ query.set(data: A(number: "1")) } } } } } struct BView: View { @Environment(\.modelContext) var context @Query private var list: [B] let query = QueryData<B>() var body: some View { VStack { if list.count > 0 { VStack { List { ForEach(list, id: \.number){ item in VStack { Text(item.number) } } } Button("clear"){ try? context.delete(model: B.self) } } } else { Button("set"){ query.set(data: B(number: "1")) } } } } } class QueryData<T: PersistentModel> { private var container: ModelContainer? init() { self.container = try? ModelContainer(for: T.self) } func set(data: T) { guard let container = self.container else { return } let context = ModelContext(container) do { try context.delete(model: T.self) context.insert(data) try context.save() } catch { print("error: \(error)") } } } @Model final class A { var number: String init(number: String) { self.number = number } } @Model final class B { var number: String init(number: String) { self.number = number } }
2
0
147
2d
SwiftUI: View is not rendered properly
Problem: When clicking on an item, it will be (un-)completed. When it's completed then ChildView should show GroupsView. However, that's not the case. The logs are like this: init, group Fruits - items not completed false - showItems false body, group Fruits - items not completed false - showItems true init, group Fruits - items not completed false - showItems false init, group Fruits - items not completed false - showItems false import SwiftUI import SwiftData @main struct MainApp: App { var body: some Scene { WindowGroup { SomeView() } .modelContainer(appContainer) } } struct SomeView: View { @Query private var items: [AItem] var body: some View { ParentView(items: items) } } struct ParentView: View { private var groupedItems: [GroupedAItems] = [] init(items: [AItem]) { Dictionary(grouping: items) { $0.categoryName } .forEach { let groupedItems = GroupedAItems(categoryName: $0.key, items: $0.value) self.groupedItems.append(groupedItems) } } var body: some View { ScrollView { VStack(spacing: 15) { ForEach(groupedItems, id: \.self.categoryName) { groupedItems in ChildView(groupedItems) } } } } } struct ChildView: View { public var groupedItems: GroupedAItems @State private var showItems: Bool init(_ groupedItems: GroupedAItems) { self.groupedItems = groupedItems self._showItems = State(initialValue: !groupedItems.completed) print("init, group \(groupedItems.categoryName) - items not completed \(!groupedItems.completed) - showItems \(showItems)") } var body: some View { print("body, group \(groupedItems.categoryName) - items not completed \(!groupedItems.completed) - showItems \(showItems)") if showItems { return AnyView(ItemsSampleView(items: groupedItems.items, onClick: { showItems = false })) } else { return AnyView(GroupsView(groupedItems: groupedItems, onClick: { showItems = true })) } } } struct ItemsSampleView: View { public var items: [AItem] public var onClick: () -> Void private let gridColumns = [GridItem(.adaptive(minimum: CGFloat(70)))] var body: some View { VStack { Button { onClick() } label: { Image(systemName: "chevron.down") } Spacer() LazyVGrid(columns: gridColumns) { ForEach(items.sorted(by: {$0.name < $1.name})) { item in Button { item.completed.toggle() } label: { Text(item.name) } } } } } } struct GroupsView: View { public var groupedItems: GroupedAItems public var onClick: () -> Void var body: some View { VStack { Button { onClick() } label: { Image(systemName: "chevron.down") } Spacer() Text(groupedItems.categoryName) } } } @Model final class AItem: Identifiable { @Attribute(.unique) public var id: String public var name: String public var categoryName: String public var completed = false internal init(name: String, categoryName: String) { self.id = UUID().uuidString self.name = name self.categoryName = categoryName } } struct GroupedAItems { var categoryName: String var items: [AItem] var completed: Bool { items.filter { !$0.completed }.isEmpty } } @MainActor let appContainer: ModelContainer = { do { let container = try ModelContainer(for: AItem.self) // Make sure the persistent store is empty. If it's not, return the non-empty container. var itemFetchDescriptor = FetchDescriptor<AItem>() itemFetchDescriptor.fetchLimit = 1 guard try container.mainContext.fetch(itemFetchDescriptor).count == 0 else { return container } container.mainContext.insert(AItem(name: "Apple", categoryName: "Fruits")) return container } catch { fatalError("Failed to create container") } }()
1
0
102
5d
SwiftData update value
Hi I want to update item value after insert. Solution(False): I want to add "isAutosaveEnabled" prop to modelContainer, but modelContainer just have one parm. Solution2(False): There doesn't have API to update SwiftData, I just find insert, delete and save. I change the city_name and run "try? modelContext.save()". But it replace after I reopen the app and maybe it doesn't work even before I close app. How can I update the city_name? /// --------- App --------- import SwiftUI import SwiftData @main struct MyApp: App { var container: ModelContainer init(){ let schema = Schema([ SD_City.self, ]) let modelConfiguration = ModelConfiguration(schema: schema) do { container = try ModelContainer(for: schema, configurations: [modelConfiguration]) let context = ModelContext(container) var city : SD_City city = SD_City(city_id: 1, city_name: "city1") context.insert(city) city = SD_City(city_id: 2, city_name: "city2") context.insert(city) } catch { fatalError("Could not create ModelContainer: ") } } var body: some Scene { WindowGroup { ContentView() } .modelContainer(container) } } /// --------- ContentView --------- import SwiftUI import SwiftData struct ContentView: View { @Environment(\.modelContext) private var modelContext @State var sortOrder_city = SortDescriptor(\SD_City.city_id) @Query(sort: [SortDescriptor(\SD_City.city_id)]) var citylist: [SD_City] @State var city_id = 0 @State var city_name = "city_name" var body: some View { HStack { Button("Change \ncity name", action: { // Update the city_name of city1 to city3 // SD_City(city_id: 1, city_name: "city1") --> SD_City(city_id: 1, city_name: "city3") }) Text(city_name) } } } /// ---------swiftdata--------- import SwiftUI import SwiftData @Model final class SD_City{ @Attribute(.unique) let city_id: Int = 1 var city_name: String = "" init(city_id: Int , city_name: String) { self.city_id = city_id self.city_name = city_name } } Thanks~
0
0
102
6d
Tabs with SwiftData
Hello folks, absolute newbie here. I'm following a tutorial that I'm trying to adjust to my own needs. In the tutorial the app is sat up in a way that you can add a new entry to a note taking app by tapping on a button which brings in an edit view. What I'm trying to do is to bring in the edit view by adding it as a tab on the bottom instead. Here's my ContentView: import SwiftData import SwiftUI struct ContentView: View { let example = Entry(content: "Example Entry") var body: some View { TabView { LifeEventsView() .tabItem { Label("Life events", systemImage: "house") } EditEntryView(entry: example) .tabItem { Label("Add new event", systemImage: "plus") } MattersView() .tabItem { Label("What matters", systemImage: "house") } } } } #Preview { ContentView() } And here's the EditEntryView: import SwiftData struct EditEntryView: View { @Bindable var entry: Entry var body: some View { Form { TextField("Entry", text: $entry.content, axis: .vertical) } .navigationTitle("Edit entry") .navigationBarTitleDisplayMode(.inline) } } #Preview { do { let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: Entry.self, configurations: config) let example = Entry(content: "Example Entry") return EditEntryView(entry: example) .modelContainer(container) } catch { fatalError("Failed to create model container.") } } The build succeeds but I get an error while running saying: Thread 1: Fatal error: failed to find a currently active container for Entry I'm sure this is an easy fix but I've been thinking with it for a while with no luck.
0
0
134
1w
Crash in Swift Data on iOS 17.5, Resolved in iOS 18.0 Developer Beta
Hey everyone, I'm a new developer working on my app. I'm facing an unusual problem during the App Store review process. The app works perfectly on my physical devices, running iOS 18.0 developer beta, but it consistently crashes on simulators with iOS 17.5. Due to this issue, my app has been rejected for iOS 17.5 because of the crashes. I know I should have avoided developing and testing the app on different versions, so please go easy on me :( Crash Details: Steps Leading to Crash: Opened the app Went to the Stocks section Clicked on Buy App crashed The Breakpoint Exception: Thread 1: EXC_BREAKPOINT (code=1, subcode=0x21b9f1620) Generated Infrastructure Code Section Triggering Crash: { @storageRestrictions(accesses: _$backingData, initializes: _stock) init(initialValue) { _$backingData.setValue(forKey: \.stock, to: initialValue) _stock = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.stock) return self.getValue(forKey: \.stock) } set { _$observationRegistrar.withMutation(of: self, keyPath: \.stock) { self.setValue(forKey: \.stock, to: newValue) } } } The crash appears to be related to Swift Data handling during the trade operation in my app's TradeView. While I've managed to temporarily fix the issue by running the app on iOS 18.0, this is not a practical solution for the App Store release, which is my immediate concern. Has anyone else experienced similar issues with Swift Data on iOS 17.5? If yes, how did you solve it? Is there a known workaround or a better approach to ensure compatibility with iOS 17.5? Thank you in advance for your valuable assistance. I truly appreciate your help!
1
0
199
6d
SwiftData Model deletion works unstable
Hi, I believe this question belongs here instead of Stack Overflow as SwiftUI + SwiftData is too new. I am using Model Context from a static Helper class: Class Helper { static let shared = Helper() var modelContext: ModelContext? } call to insert data on the 1st screen: Helper.shared.modelContext?.insert(item) Query Model declaration on the 1st screen: @Query private var products: [ProductModel] also autoSave turned to false: .onAppear{ Helper.shared.modelContext?.autosaveEnabled = false } periodically update data via a standard Timer object: for item in products { item.price = 500 } SwiftData works just fine in this 1st screen, but when we try to delete the Model and move on to next screen, we found out memory of the previous screen Model (ProductModel) in this case is still persisted and keep increasing! Eventually causing hang in the 2nd screen. Model deletion code in onDisappear of the 1st screen: .onDisappear{ try? Helper.shared.modelContext?.delete(model: ProductModel.self) try? Helper.shared.modelContext?.save() } Any clue where we might be wrong? Thanks
1
0
115
4d
Importing Data into SwiftData in the Background Using ModelActor and @Query
I have an app with fairly typical requirements - I need to insert some data (in my case from the network but could be anything) and I want to do it in the background to keep the UI responsive. I'm using SwiftData. I've created a ModelActor that does the importing and using the debugger I can confirm that the data is indeed being inserted. On the UI side, I'm using @Query and a SwiftUI List to display the data but what I am seeing is that @Query is not updating as the data is being inserted. I have to quit and re-launch the app in order for the data to appear, almost like the context running the UI isn't communicating with the context in the ModelActor. I've included a barebones sample project. To reproduce the issue, tap the 'Background Insert' button. You'll see logs that show items being inserted but the UI is not showing any data. I've tested on the just released iOS 18b3 seed (22A5307f). The sample project is here: https://hanchor.s3.amazonaws.com/misc/SwiftDataBackgroundV2.zip
2
1
218
5d
SwiftData: externalStorage attribute on ios18
Hello, I'm experiencing an issue with iOS 18 Beta 3 and SwiftData. I have a model with some attributes marked as externalStorage because they are pretty large. In iOS 17 I could display a list of all my Models and it would not prefetch the externalStorage attributes. Now in iOS 18 it seems the attributes are fetched even though I don't use them in my list. It's an issue because the memory use of my app goes from 100mo on iOS 17 to more than 1gb on iOS 18 because of this. My app is configured to sync with iCloud. Anyone else experiencing the issue? Thanks Gil
2
1
153
2d
Multiple relationship variables of the the same type
Want to know if it's possible to have multiple variables of the same type? This code works but when the app loads the data again on relaunch, both variables have both the new cards and discarded cards. @Model class Player { let id = UUID() let name: String @Relationship(deleteRule: .cascade, inverse: \Card.player) var cards: [Card] = [] @Relationship(deleteRule: .cascade, inverse: \Card.player) var discardedCards: [Card] = [] init(name: String, cards: [Card]) { self.name = name self.cards = cards } } @Model class Card { let id = UUID() let name: String var player: Player? init(name: String) { self.name = name } }
0
0
100
1w
SwiftData ModelConfiguration with GroupContainer shows Data Access alert on every launch
I'm building an app which has both iOS and macOS versions along with extensions on both platforms. I want the main app to be able to share data the extension using the group container and I want the app on both platforms sync data over CloudKit. CloudKit synchronization works like a dream. The data sharing between the app and extension on iOS works also exactly as intended. However on macOS every time the app is launched I get “MyApp” would like to access data from other apps. alert dialog. I tried initializing the ModelConfiguration both with an explicit and automatic app group container identifiers. Same results.
1
0
151
1w
Have a Multiplatform app, cannot test my app that uses App Groups properly
Dear Apple Developer Forum community, I have a Multiplatform SwiftUI app that runs on both iOS and macOS. The app is available in the Mac App Store, and I aim to maintain backward compatibility. I use App Groups to synchronize data between the main app, where users configure content, and the widget, which displays this content. The data is stored using SwiftData. With macOS Sequoia now in beta testing, I have encountered a breaking change that affects my app. In macOS Sequoia, apps must use the team identifier number $(TeamIdentifierPrefix) as the prefix for App Groups on macOS. I cannot properly test future versions of my app without instructing my beta testers to turn off System Integrity Protection (SIP). This presents a significant issue for my Multiplatform SwiftUI app. On iOS, the app group identifier must start with group.identifier. Before macOS Sequoia, you could name your app group freely, and testing with TestFlight and publishing to the App Store was straightforward. Now, however, testing an app intended for the App Store is complicated by this rule. On macOS, you must use $(TeamIdentifierPrefix) to bypass this rule and allow for widgets to be tested and allow for synchronization between SwiftData. While on iOS, this approach is not allowed as the App Group becomes considered invalid. Additionally, this annoying popup appears every time a beta tester tries to open the app if they have SIP turned on: Instead of prompting for the app extensions, it rejects it. Rejecting this popup also prevents the main SwiftData app from opening. I am unsure how to proceed. If I want to test widgets (which is a primary focus of the app), I must use macOS Sequoia. I am particularly concerned about the implications if I decide to stop supporting macOS Sonoma in the future. Thank you in advance, LocalWE
3
1
246
6d