I see a chunk load error in the browser console.
I already reported this: FB17664487
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello,
I am trying to access my cloudkit database from the icloud developer dashboard but I am getting the following error:
Error looking up Developer Teams
XHR request failure
Please sign out and try again.
I tried signing out but the error persists,
Thanks
Hi all,
has anybody found the trick how to get SwiftData working with SpotLight Search?
Setting the attribute "spotlight" in the Model definition seems to do nothing at all, as pointed out by Paul Hudson in his new book as well
(https://www.hackingwithswift.com/quick-start/swiftdata/how-to-index-swiftdata-objects-in-spotlight)
Thanks a lot!
I have a project that currently has data saved locally and I'm trying to get it to sync over multiple devices.
Currently basic data is syncing perfectly fine, but I'm having issues getting the images to convert to data. From what I've researched it because I'm using a UIImage to convert and this caches the image
It works fine when there's only a few images, but if there's several its a pain
The associated code
func updateLocalImages() {
autoreleasepool {
let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "converted = %d", false)
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Project.statusOrder?.sortOrder, ascending: true), NSSortDescriptor(keyPath: \Project.name, ascending: true)]
do {
let projects = try viewContext.fetch(fetchRequest)
for project in projects {
currentPicNumber = 0
currentProjectName = project.name ?? "Error loading project"
if let pictures = project.pictures {
projectPicNumber = pictures.count
for pic in pictures {
currentPicNumber = currentPicNumber + 1
let picture : Picture = pic as! Picture
if let imgData = convertImage(picture: picture) {
picture.pictureData = imgData
}
}
project.converted = true
saveContext()
}
}
} catch {
print("Fetch Failed")
}
}
}
func convertImage(picture : Picture)-> Data? {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let path = paths[0]
if let picName = picture.pictureName {
let imagePath = path.appendingPathComponent(picName)
if let uiImage = UIImage(contentsOfFile: imagePath.path) {
if let imageData = uiImage.jpegData(compressionQuality: 0.5) {
return imageData
}
}
}
return nil
}```
I’m getting a 0xdead10cc crash in a basic CoreData/CloudKit application. I only have one CoreData save call and its made when the app is in the foreground and it's minor so I don't think its being caused by that. My best guess is that it's related to background syncing of CloudKit. Does anyone know how to fix it? I've been advised that adding the following code around any saves will fix it, but it seems weird that this is the solution. I would expect the inner CoreData/CloudKit engine to handle this.
ProcessInfo().performActivity(reason: "Persisting to context") {
// Save to context here
}
Here is the crashing thread
Thread 7:
0 libsystem_kernel.dylib 0x00000001edc086f4 guarded_pwrite_np + 8 (:-1)
1 libsqlite3.dylib 0x00000001ca71b6e4 seekAndWrite + 456 (sqlite3.c:44287)
2 libsqlite3.dylib 0x00000001ca6d5df4 unixWrite + 180 (sqlite3.c:44365)
3 libsqlite3.dylib 0x00000001ca723b90 pagerWalFrames + 872 (sqlite3.c:67093)
4 libsqlite3.dylib 0x00000001ca6d5b14 sqlite3PagerCommitPhaseOne + 316 (sqlite3.c:70409)
5 libsqlite3.dylib 0x00000001ca6c6494 sqlite3BtreeCommitPhaseOne + 172 (sqlite3.c:81106)
6 libsqlite3.dylib 0x00000001ca6c605c vdbeCommit + 1136 (sqlite3.c:94124)
7 libsqlite3.dylib 0x00000001ca69f778 sqlite3VdbeHalt + 1340 (sqlite3.c:94534)
8 libsqlite3.dylib 0x00000001ca6c0618 sqlite3VdbeExec + 42648 (sqlite3.c:103922)
9 libsqlite3.dylib 0x00000001ca6b56c0 sqlite3_step + 960 (sqlite3.c:97886)
10 CoreData 0x00000001a459ab38 _execute + 128 (NSSQLiteConnection.m:4614)
11 CoreData 0x00000001a45fe004 -[NSSQLiteConnection commitTransaction] + 728 (NSSQLiteConnection.m:3278)
12 CoreData 0x00000001a469888c _executeGenerateObjectIDRequest + 388 (NSSQLCore_Functions.m:6021)
13 CoreData 0x00000001a46986a4 -[NSSQLGenerateObjectIDRequestContext executeRequestCore:] + 28 (NSSQLObjectIDRequestContext.m:42)
14 CoreData 0x00000001a45fb380 -[NSSQLStoreRequestContext executeRequestUsingConnection:] + 240 (NSSQLStoreRequestContext.m:183)
15 CoreData 0x00000001a45fb0a8 __52-[NSSQLDefaultConnectionManager handleStoreRequest:]_block_invoke + 60 (NSSQLConnectionManager.m:307)
16 CoreData 0x00000001a45fafe0 __37-[NSSQLiteConnection performAndWait:]_block_invoke + 48 (NSSQLiteConnection.m:755)
17 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576)
18 libdispatch.dylib 0x00000001a43677fc _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1104)
19 CoreData 0x00000001a45b5ba4 -[NSSQLiteConnection performAndWait:] + 176 (NSSQLiteConnection.m:752)
20 CoreData 0x00000001a45b5a68 -[NSSQLDefaultConnectionManager handleStoreRequest:] + 248 (NSSQLConnectionManager.m:302)
21 CoreData 0x00000001a45b5938 -[NSSQLCoreDispatchManager routeStoreRequest:] + 228 (NSSQLCoreDispatchManager.m:60)
22 CoreData 0x00000001a45b573c -[NSSQLCore dispatchRequest:withRetries:] + 172 (NSSQLCore.m:4044)
23 CoreData 0x00000001a46737b4 -[NSSQLCore _obtainPermanentIDsForObjects:withNotification:error:] + 1324 (NSSQLCore.m:2830)
24 CoreData 0x00000001a460ba98 -[NSSQLCore _prepareForExecuteRequest:withContext:error:] + 272 (NSSQLCore.m:2946)
25 CoreData 0x00000001a460a0f8 __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.547 + 8988 (NSPersistentStoreCoordinator.m:2995)
26 CoreData 0x00000001a45d6660 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:] + 264 (NSPersistentStoreCoordinator.m:668)
27 CoreData 0x00000001a45ded28 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 1200 (NSPersistentStoreCoordinator.m:2810)
28 CoreData 0x00000001a4655988 -[NSManagedObjectContext save:] + 984 (NSManagedObjectContext.m:1593)
29 CoreData 0x00000001a46f47dc __52+[NSCKEvent beginEventForRequest:withMonitor:error:]_block_invoke_2 + 352 (NSCKEvent.m:76)
30 CoreData 0x00000001a45c28f0 developerSubmittedBlockToNSManagedObjectContextPerform + 476 (NSManagedObjectContext.m:3984)
31 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576)
32 libdispatch.dylib 0x00000001a43677fc _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1104)
33 CoreData 0x00000001a4615c34 -[NSManagedObjectContext performBlockAndWait:] + 308 (NSManagedObjectContext.m:4108)
34 CoreData 0x00000001a46f45ac __52+[NSCKEvent beginEventForRequest:withMonitor:error:]_block_invoke + 192 (NSCKEvent.m:66)
35 CoreData 0x00000001a4825e68 -[PFCloudKitStoreMonitor performBlock:] + 92 (PFCloudKitStoreMonitor.m:148)
36 CoreData 0x00000001a46f4394 +[NSCKEvent beginEventForRequest:withMonitor:error:] + 256 (NSCKEvent.m:61)
37 CoreData 0x00000001a47cc6ec __57-[NSCloudKitMirroringDelegate _performExportWithRequest:]_block_invoke + 260 (NSCloudKitMirroringDelegate.m:1433)
38 CoreData 0x00000001a47c9970 __92-[NSCloudKitMirroringDelegate _openTransactionWithLabel:assertionLabel:andExecuteWorkBlock:]_block_invoke + 72 (NSCloudKitMirroringDelegate.m:957)
39 libdispatch.dylib 0x00000001a4356248 _dispatch_call_block_and_release + 32 (init.c:1549)
40 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576)
41 libdispatch.dylib 0x00000001a435f5cc _dispatch_lane_serial_drain + 768 (queue.c:3934)
42 libdispatch.dylib 0x00000001a4360158 _dispatch_lane_invoke + 432 (queue.c:4025)
43 libdispatch.dylib 0x00000001a436b38c _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:7193)
44 libdispatch.dylib 0x00000001a436abd8 _dispatch_workloop_worker_thread + 540 (queue.c:6787)
45 libsystem_pthread.dylib 0x0000000227213680 _pthread_wqthread + 288 (pthread.c:2696)
46 libsystem_pthread.dylib 0x0000000227211474 start_wqthread + 8 (:-1)
Hello,
I have a problem with SwiftData and Predicates that check for the persistentModelID of the relations.
My data model looks simplified like this:
Day -> TimeEntry[] -> Hashtag[]
What I want to achieve is to query the days and associated time entries via assigned tags.
This is my predicate:
let identifier = filterHashtags.map(\.persistentModelID)
...
#Predicate<TimeEntry> { timeEntry in
identifiers.count == timeEntry.tags.filter { tag in
identifiers.contains(tag.persistentModelID)
}.count
}
It does not return any data when I check for the persistentModelID. However, if I use another property of the tags, e.g. the name or a generated UUID for the check, the predicate works. Is this a general problem with PersistentIdentifier in Predicates or am I missing something?
Thanks in advance
When I tried to use a working project with iOS 18 installed on my device, it wouldn't work anymore and crash right away. Before with iOS 17 it was working fine.
I can't access child variables that are saved in an Array in a parent object in SwiftData. The error is always somewhere in these hidden lines:
{
@storageRestrictions(accesses: _$backingData, initializes: _title)
init(initialValue) {
_$backingData.setValue(forKey: \.title, to: initialValue)
_title = _SwiftDataNoType()
}
get {
_$observationRegistrar.access(self, keyPath: \.title)
return self.getValue(forKey: \.title)
}
set {
_$observationRegistrar.withMutation(of: self, keyPath: \.title) {
self.setValue(forKey: \.title, to: newValue)
}
}
}
The child classes are also inserted and saved into the modelContext when created and set to the parent instance, but I also can't fetch them via modelContext.fetch() - Error here is:
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x243a62a4c)
Maybe there is a problem with the relationship between two saved instances.
The parent instances are saved correctly and it was working in iOS 17.
The problem is similar to these two cases:
https://forums.developer.apple.com/forums/thread/762679
https://forums.developer.apple.com/forums/thread/738983
I changed the logic after I reviewed these threads, as I am now linking the parent and child instances, that got rid of one warning in the console.
button.canvas = canvas
modelContext.insert(button)
canvas.buttons = [button]
But in the end those threads were not enough for me to find a fix for my problem.
A small project can be found here:
https://github.com/DonMalte/SwiftDataTest
Topic:
App & System Services
SubTopic:
iCloud & Data
No matter what I do, I keep getting the error Thread 1: EXC_BREAKPOINT (code=1, subcode=0x2648fc364) for the line: transactions = try modelContext.fetch(descriptor) in the code below. My app opens, but freezes on the home page and I can't click anything. I am not sure how to fix initialization issues. I am creating a financial assistant app that connects plaid and opoenai api.
var descriptor = FetchDescriptor<ExpenseTransaction>()
descriptor.sortBy = [SortDescriptor(\.date, order: .reverse)]
descriptor.fetchLimit = 200
transactions = try modelContext.fetch(descriptor)
print("Successfully loaded \(transactions.count) transactions")
} catch {
print("Error in loadLocalTransactions: \(error)")
transactions = []
}
}
I have been dealing with an error for almost 2 days now that caused my programme to crash on runtime with Thread 10: EXC_BAD_ACCESS (code=1, address=0x0) error , only when using Release mode.
After many trial and errors and narrowing down the root problem I became suspicious to #Predicate and Generics being the root cause of the problem so I made these views to test it out.
import SwiftUI
import SwiftData
struct DataBaseTestGeneric<Model : PersistentModel>: View {
@State private var models: [Model] = []
var body: some View {
viewLoader{
let reporter = Reporter()
let pred = #Predicate<Model>{ model in
return true
}
models = await reporter.fetch(pred)
}content: {
List{
ForEach(models){ model in
Text("\(model.id)")
}
}
}
}
}
and a non-Generic version :
import SwiftData
struct DatabaseTest: View {
@State private var transactions: [Transaction] = []
var body: some View {
viewLoader {
let reporter = Reporter()
let pred = #Predicate<Transaction>{ dec in
return true
}
let decs = await reporter.fetch(pred)
transactions = decs
}content:{
List{
ForEach(transactions){transaction in
Text("\(transaction.id)")
}
}
}
}
}
to give you an insight viewLoader implentations is :
struct viewLoader<Content : View>: View {
var state : LoadingView.States = .loading
let loadingTask : () async -> Void
@State private var isLoading = true
@ViewBuilder var content : Content
var body: some View {
if isLoading{
LoadingView(state)
.task {
await Task.detached(priority:.high){
await loadingTask()
}.value
isLoading = false
}
}else{
content
}
}
}
and I am accessing SwiftData using a background thread ( by implementing @ModelActor . the problem is that the code always crash on runtime when I am trying to fetch the data using reporter.fetch function.
To make things even more weird I have to add the fact that Reporter class also have another function called fetchAll as follow :
func fetchAll<T>(_ model : T.Type) async -> [T] where T : PersistentModel {
let desc = FetchDescriptor<T>()
let result = try? await context.fetch(desc)
guard let result else {
assertionFailure("Error fetching \(model) from context")
return []
}
return result
}
if i replace this function with reporter.fetch (which takes a predicate) the code will not crash either with or without using Generics , which brings me to the point that #Predicate is causing mayhem somehow !
PS: I am using Xcode Version 16.1 (16B40) , on macOs Sequoia Version 15.2 Beta (24C5089c)
I have made a Swift App for MacOS 15 under XCode 16.3, which runs fine. I also want to run it under the previous MacOS 14. Unfortunately it crashes without even starting up (it does not even reach the first log output statement on the first view)
The crash reason is
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x0000000000000000
Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4
Terminating Process: exc handler [2970]
I have set the miminium deployment to MacOS 14.0 but to no effect. The XCode machine is a MacOS 15.4 on Arm M3 and the target machine is MacOS 14.7.5 on Intel (MacBook Air)
I think it might be related to the compiler and linker settings.
Hello,
I’m struggling to go from unversioned data model in SwiftData, to starting to version it.
Some FYI:
I’m using CloudKit
I’m using a widget, where I also pass in my data model and setup my container, this is shared over a group container/app group.
My migration is very simple, I’m adding a property which is not optional ( has default value set, and a default value in initialiser ).
Model:
@Model
class NicotineModel {
var nicotineType: NicotineType = NicotineType.snus
var startDate: Date = Date() + 30
var spendingAmount: Int = 0
var nicotinePerDay: Int = 0
var quittingMethod: QuittingMethod = QuittingMethod.coldTurkey // this is the change in the model, V1 doesn't have the quittingMethod property
var setupComplete: Bool = false
I’ve tried with:
static let migrateV1toV2 = MigrationStage.lightweight(
fromVersion: SchemaV1.self,
toVersion: SchemaV2.self
)
But also
static let migrateV1toV2 = MigrationStage.custom(
fromVersion: SchemaV1.self,
toVersion: SchemaV2.self,
willMigrate: nil,
didMigrate: {
context in
let nicotineModels2 = try context.fetch(FetchDescriptor<SchemaV2.NicotineModel>())
let nicotineModels = try context.fetch(FetchDescriptor<SchemaV1.NicotineModel>())
for model in nicotineModels {
let newModel = SchemaV2.NicotineModel(
nicotineType: model.nicotineType,
startDate: model.startDate,
spendingAmount: model.spendingAmount,
nicotinePerDay: model.nicotinePerDay,
setupComplete: model.setupComplete,
quittingMethod: .coldTurkey
)
context.insert(newModel)
context.delete(model)
}
try context.save()
}
)
and simply
static let migrateV1toV2 = MigrationStage.custom(
fromVersion: SchemaV1.self,
toVersion: SchemaV2.self,
willMigrate: nil,
didMigrate: { context in
let nicotineModels = try context.fetch(FetchDescriptor<SchemaV2.NicotineModel>())
for model in nicotineModels {
model.quittingMethod = .coldTurkey
}
try context.save()
}
)
This gives me the error on startup
SwiftData/ModelCoders.swift:1762: Fatal error: Passed nil for a non-optional keypath \NicotineModel.quittingMethod
On https://icloud.developer.apple.com I can see that the record doesn't include my quittingMethod.
I'm loosing my mind, what am I doing wrong?
I'm working through the Develop In Swift tutorial at page
[https://developer.apple.com/tutorials/develop-in-swift/navigation-editing-and-relationships-conclusion)]
The tutorial has a one to many relationship between Friend and Movie (each friend can have at most one favorite movie and each movie can be the favorite for zero or more friends).
An exercise left to the student is to use an .onDelete on the movie detail page to delete that movie as favorite.
I modified the Form
Form {
TextField("Movie title", text: $movie.title)
DatePicker("Release date", selection: $movie.releaseDate, displayedComponents: .date)
if !movie.favoritedBy.isEmpty {
Section("Favorited by") {
ForEach(sortedFriends) { friend in
Text(friend.name)
}
.onDelete(perform: deleteFavorites(indexes:))
}
}
}
by adding the .onDelete clause
I added
private func deleteFavorites(indexes: IndexSet) {
for index in indexes {
context.delete(movie.favoritedBy[index])
}
}
to the view.
This does delete the favorite movie, but it also deletes the friend. My assumption is that the selected friend should then have no favorite movie rather than being deleted
There is an if in the Form that doesn't display the FAVORITED BY section if no friend has that movie as a favorite, but if I delete all the friends who had this movie as a favorite, the section remains (but is empty), until I exit the MovieDetail view and reload it
There is no answer for these exercises, so I could be doing it wrong.
EDIT: If I delete a movie using the app function to delete a movie, friends that have that movie as a favorite are not deleted and have their favorite movie set to None
I am using cloudkit to save users high scores in a public database. The preference over using Game Center is because of simplicity and works really well for what I want to achieve. I simply want to let users know their global position. Because of data privacy laws the app asks the user for their permission to submit their score each time they get a new high score.
However, I have noticed that CKRecords under 'created' and 'modified' in addition to UTC time and date also contain creatorUserRecordID. Could this be a privacy issue? Can you extract any personal information from this? Can this be used to track back to the user? Is it linked to CKUserIdentity which I understand does contain personal information, although as I understand you need users consent to get this information. Under creatorUserRecordID it says... "Every user of the app has a unique user record that is empty by default. Apps can add data to the user record on behalf of the user, but don’t store sensitive data in it"
Currently I simply ask the user if they are happy to submit their score. But do I need to point out that it also stores a creatorUserRecordID? Obviously I don't want to do this if it is not needed as the user will 1) Probably not understand what a creatorUserRecordID is and 2) It makes the question complicated and will likely make most people refuse to submit their score.
If it is a privacy issue, is there anyway to stop a CKRecord creating this ID and simply save a score? All I need is a list of scores so the app can determine their current position.
If creatorUserRecordID does not contain any personal details and cannot be tracked back to the user please let me know, so I can be reassured that my current set up is fine and I am not causing any privacy issues!
This post did seem to indicate you may possibly be able to fetch personal details??
https://stackoverflow.com/questions/55782166/how-do-i-fetch-any-info-about-user-that-modified-ckrecord
I'm developing a SwiftUI app using SwiftData and encountering a persistent issue:
Error Message:
Thread 1: Fatal error: Duplicate keys of type 'Bland' were found in a Dictionary.
This usually means either that the type violates Hashable's requirements, or that members of such a dictionary were mutated after insertion.
Details:
Occurrence: The error always occurs on the first launch of the app after installation. Specifically, it happens approximately 1 minute after the app starts.
Inconsistent Behavior: Despite no changes to the code or server data, the error occurs inconsistently.
Data Fetching Process:
I fetch data for entities (Bland, CrossZansu, and Trade) from the server using the following process:
Fetch Bland and CrossZansu entities via URLSession.
Insert or update these entities into the SwiftData context.
The fetched data is managed as follows:
func refleshBlandsData() async throws {
if let blandsOnServer = try await DataModel.shared.getBlands() {
await MainActor.run {
blandsOnServer.forEach { blandOnServer in
if let blandOnLocal = blandList.first(where: { $0.code == blandOnServer.code }) {
blandOnLocal.update(serverBland: blandOnServer)
} else {
modelContext.insert(blandOnServer.bland)
}
}
}
}
}
This is a simplified version of my StockListView. The blandList is a @Query property and dynamically retrieves data from SwiftData:
struct StockListView: View {
@Environment(\.modelContext) private var modelContext
@Query(sort: \Bland.sname) var blandList: [Bland]
@Query var users: [User]
@State private var isNotLoaded = true
@State private var isLoading = false
@State private var loadingErrorState = ""
var body: some View {
NavigationStack {
List {
ForEach(blandList, id: \.self) { bland in
NavigationLink(value: bland) {
Text(bland.sname)
}
}
}
.navigationTitle("Stock List")
.onAppear {
doIfFirst()
}
}
}
// This function handles data loading when the app launches for the first time
func doIfFirst() {
if isNotLoaded {
loadDataWithAnimationIfNotLoading()
isNotLoaded = false
}
}
// This function ensures data is loaded with an animation and avoids multiple triggers
func loadDataWithAnimationIfNotLoading() {
if !isLoading {
isLoading = true
Task {
do {
try await loadData()
} catch {
// Capture and store any errors during data loading
loadingErrorState = "Data load failed: \(error.localizedDescription)"
}
isLoading = false
}
}
}
// Fetch data from the server and insert it into the SwiftData model context
func loadData() async throws {
if let blandsOnServer = try await DataModel.shared.getBlands() {
for bland in blandsOnServer {
// Avoid inserting duplicate keys by checking for existing items in blandList
if !blandList.contains(where: { $0.code == bland.code }) {
modelContext.insert(bland.bland)
}
}
}
}
}
Entity Definitions:
Here are the main entities involved:
Bland:
@Model
class Bland: Identifiable {
@Attribute(.unique) var code: String
var sname: String
@Relationship(deleteRule: .cascade, inverse: \CrossZansu.bland)
var zansuList: [CrossZansu]
@Relationship(deleteRule: .cascade, inverse: \Trade.bland)
var trades: [Trade]
}
CrossZansu:
@Model
class CrossZansu: Equatable {
@Attribute(.unique) var id: String
var bland: Bland?
}
Trade:
@Model
class Trade {
@Relationship(deleteRule: .nullify)
var user: User?
var bland: Bland
}
User:
class User {
var id: UUID
@Relationship(deleteRule: .cascade, inverse: \Trade.user)
var trades: [Trade]
}
Observations:
Error Context: The error occurs after the data is fetched and inserted into SwiftData. This suggests an issue with Hashable requirements or duplicate keys being inserted unintentionally.
Concurrency Concerns: The fetch and update operations are performed in asynchronous tasks. Could this cause race conditions?
Questions:
Could this issue be related to how @Relationship and @Attribute(.unique) are managed in SwiftData?
What are potential pitfalls with Equatable implementations (e.g., in CrossZansu) when used in SwiftData entities?
Are there any recommended approaches for debugging "Duplicate keys" errors in SwiftData?
Additional Info:
Error Timing: The error occurs only during the app's first launch and consistently within the first minute.
Hi guys. Can someone please confirm this bug so I report it? The issue is that SwiftData relationships don't update the views in some specific situations on devices running iOS 18 Beta. One clear example is with CloudKit. I created a small example for testing. The following code creates two @models, one to store bands and another to store their records. The following code works with no issues. (You need to connect to a CloudKit container and test it on two devices)
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var records: [Record]
var body: some View {
NavigationStack {
List(records) { record in
VStack(alignment: .leading) {
Text(record.title)
Text(record.band?.name ?? "Undefined")
}
}
.toolbar {
ToolbarItem {
Button("Add Record") {
let randomNumber = Int.random(in: 1...100)
let newBand = Band(name: "New Band \(randomNumber)", records: nil)
modelContext.insert(newBand)
let newRecord = Record(title: "New Record \(randomNumber)", band: newBand)
modelContext.insert(newRecord)
}
}
}
}
}
}
@Model
final class Record {
var title: String = ""
var band: Band?
init(title: String, band: Band?) {
self.title = title
self.band = band
}
}
@Model
final class Band {
var name: String = ""
var records: [Record]?
init(name: String, records: [Record]?) {
self.name = name
self.records = records
}
}
This view includes a button at the top to add a new record associated with a new band. The data appears on both devices, but if you include more views inside the List, the views on the second device are not updated to show the values of the relationships. For example, if you extract the row to a separate view, the second device shows the relationships as "Undefined". You can try the following code.
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var records: [Record]
var body: some View {
NavigationStack {
List {
ForEach(records) { record in
RecordRow(record: record)
}
}
.toolbar {
ToolbarItem {
Button("Add Record") {
let randomNumber = Int.random(in: 1...100)
let newBand = Band(name: "New Band \(randomNumber)", records: nil)
modelContext.insert(newBand)
let newRecord = Record(title: "New Record \(randomNumber)", band: newBand)
modelContext.insert(newRecord)
}
}
}
}
}
}
struct RecordRow: View {
let record: Record
var body: some View {
VStack(alignment: .leading) {
Text(record.title)
Text(record.band?.name ?? "Undefined")
}
}
}
Here I use a ForEach loop and move the row to a separate view. Now on the second device the relationships are nil, so the row shows the text "Undefined" instead of the name of the band.
I attached an image from my iPad. I inserted all the information on my iPhone. The first three rows were inserted with the first view. But the last two rows were inserted after I extracted the rows to a separate view. Here you can see that the relationships are nil and therefore shown as "Undefined". The views are not updated to show the real value of the relationship.
This example shows the issue with CloudKit, but this also happens locally in some situations. The system doesn't detect updates in relationships and therefore doesn't refresh the views.
Please, let me know if you can reproduce the issue. I'm using Mac Sequoia 15.1, and two devices with iOS 18.0.
iOS 18.2, Swift, Xcode 16.2
I have a Core Data model with two entities - WarehouseArea (of which there is only one object) and StockReeipt (of which there are a couple of hundred thousand). Each StockReceipt must be linked to a WarehouseArea, and a WarehouseArea can be linked to zero, one or many StockReceipts.
My problem is that when I create and add one more StockReceipt, the Core Data save takes over 3 seconds to complete. I don't understand why this is so slow. Saving the initial 200,000 StockReceipts only takes 5-6 seconds.
When I enable SQL logging I can see that when the WarehouseArea attribute is being set on a StockReceipt, Core Data fetches all of the other StockReceipts (I don't know why) but that only takes 0.2 seconds and none of those StockReceipts are modified, so there shouldn't be any need to process them when saving the context.
I have prepared a test project which can be found at https://github.com/DaleReilly/CoreDataSaveTester . Running the project will produce NSLog output showing the times before and after the slow save.
Please help me understand what is going on in the background and tell me if there is any way I can speed this up?
Topic:
App & System Services
SubTopic:
iCloud & Data
Here we have yet another bug, I suppose, in SwiftData that happens on iOS18 but it is not an issue on iOS17.
There are 2 models defined as follows
@Model
final public class Note: Identifiable, Codable, Hashable
{
public private(set) var uuid = UUID().uuidString
var heading: String = ""
var tags: [Tag]?
init(heading: String = "") {
self.heading = heading
}
required public init(from decoder: Decoder) throws {
...
}
public func encode(to encoder: Encoder) throws {
...
}
}
@Model
final public class Tag: Identifiable, Codable
{
var name: String = ""
@Relationship(deleteRule: .nullify, inverse: \Note.tags) var notes: [Note]?
init(_ name: String) {
self.name = name
}
required public init(from decoder: Decoder) throws {
…
}
public func encode(to encoder: Encoder) throws {
...
}
}
and a function o add new tags as follows
private func addTags(note: Note, tagNames: [String]) {
if note.tags == nil {
note.tags = []
}
for tagName in tagNames {
if let tag = fetchTag(tagName) {
if !note.tags!.contains(where: {$0.name == tagName}) {
note.tags!.append(tag)
}
} else {
// The following line throws the exception on iOS18 when Tag conforms to Codable:
// Illegal attempt to map a relationship containing temporary objects to its identifiers.
note.tags!.append(Tag(tagName))
}
}
}
This code works perfectly well on iOS17 but on iOS18 I get the exception “Illegal attempt to map a relationship containing temporary objects to its identifiers.”
What I noticed that this happens only when Tag model conforms to Codable protocol. Is it a bug? It looks like, otherwise we've got some undocumented changes have been made.
In my previous post I mentioned about the other issue about ModelContext that is broken too on iOS18 - I mean it works perfectly well on iOS17.
Demo app with an example how to workaround this problem is available here on GitHub.
Repro steps:
Add a note with some tags (separated by space)
Edit this note and add a new tag (tag that does not exists in database) and tap Save.
You should noticed that the tag hasn't been added. It works occasionally but hardly to be seen.
I have an app that starts a Live Activity on a certain user action. This Live Activity contains a button that the user can tap, which updates a SwiftData model instance. However, when you return to the main app after tapping the button on the Live Activity, the views do not update to reflect the changes, even though the changes were written to the database.
The underlying issue here is that the ModelContainer/ModelContext used by the AppIntent (performed from the LiveActivity when the button is tapped), are different from the instances in the main app. Meaning that while the changes are written to the underlying storage, the in-memory instances of ModelContext/ModelContainer in the main app don't get the changes from the extension, so SwiftUI doesn't update either.
What is the recommended way to handle this scenario? Or is there one? :) Shared access to a SwiftData container is clearly supported through App Groups, so is there not a mechanism to ensure changes made by an extension are updated in real-time for the main app?
Otherwise, it seems I would have to go through and manually rerun queries that views depend on to make sure they are showing the most recent data. This is cumbersome and error-prone.
Perhaps I'm missing something? Any suggestions would be greatly appreciated.
I'm using SwiftData with CloudKit and have been trying to migrate from
SchemaV1 to SchemaV2, but it seems reducing the Entities crashes my app.
// Example of migrating from V1 to V2
// Dropping `Person` because it's no longer needed
do {
// SchemaV1: Person.self, Author.self
// SchemaV2: Author.self
let schema = Schema(versionedSchema: SchemaV2.self)
return try ModelContainer(
for: schema,
migrationPlan: AppSchemaMigrationPlan.self,
configurations: ModelConfiguration(
cloudKitDatabase: .automatic)
)
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
Is it possible to drop Entities in the Schema Migration Plan?
How can I delete the Person model from my Schema and CloudKit?
Hi,
I'm building a habit tracking app for iOS and macOS. I want to use up to date technologies, so I'm using SwiftUI and SwiftData.
I want to store user data locally on device and also sync data between device and iCloud server so that the user could use the app conveniently on multiple devices (iPhone, iPad, Mac).
I already tried SwiftData + NSPersistentCloudKitContainer, but I need to control when to sync data, which I can't control with NSPersistentCloudKitContainer. For example, I want to upload data to server right after data is saved locally and download data from server on every app open, on pull-to-refresh etc. I also need to monitor sync progress, so I can update the UI and run code based on the progress. For example, when downloading data from server to device is in progress, show "Loading..." UI, and when downloading finishes, I want to run some app business logic code and update UI.
So I'm considering switching from NSPersistentCloudKitContainer to CKSyncEngine, because it seems that with CKSyncEngine I can control when to upload and download data and also monitor the progress.
My database schema (image below) has relationships - "1 to many" and "many to many" - so it's convenient to use SwiftData (and underlying CoreData).
Development environment: Xcode 16.1, macOS 15.1.1
Run-time configuration: iOS 18.1.1, macOS 15.1.1
My questions:
1-Is it possible to use SwiftData for local data storage and CKSyncEngine to sync this local data storage with iCloud?
2-If yes, is there any example code to implement this?
I've been studying the "CloudKit Samples: CKSyncEngine" demo app (https://github.com/apple/sample-cloudkit-sync-engine), but it uses a very primitive approach to local data storage by saving data to a JSON file on disk.
It would be very helpful to have the same demo app with SwiftData implementation!
3-Also, to make sure I don't run into problems later - is it okay to fire data upload (sendChanges) and download (fetchChanges) manually with CKSyncEngine and do it often? Are there any limits how often these functions can be called to not get "blocked" by the server?
4-If it's not possible to use SwiftData for local data storage and CKSyncEngine to sync this local data storage with iCloud, then what to use for local storage instead of SwiftData to sync it with iCloud using CKSyncEngine? Maybe use SwiftData with the new DataStore protocol instead of the underlying CoreData?
All information highly appreciated!
Thanks,
Martin
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
Cloud and Local Storage
SwiftUI
SwiftData