After updating to iOS 18, my phone started crashing, and several apps stopped working. Every time I try to open them, they just crash. I tried reinstalling the apps, but the problem persisted. I even reset my phone to factory settings, but it kept the same iOS 18 version, even without any of my current apps. It seems like the iOS version is tied to my Apple ID rather than just my phone.
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Post
Replies
Boosts
Views
Activity
I took one of my apps and have gone through the process of making it compatible with Swift 6. I started with Swift 5 and Complete Concurrency Checking and eliminated every warning. I flipped the switch to Swift 6 and I have no compile errors and no warnings. I also created a ModelActor and created async functions to fetch, delete, get an object's persistentID and save model objects. My SwiftData model has a notes property and the user can update or add onto the notes and resave the model object. The app crashes when I save the changes using an explicit save operation. However, the next time the app is launched, the changes did propagate. If I do not use the explicit save operation, the system does not auto-save and does not crash.
When I switched back to Swift 5 and tried it out, I was able to save without a crash. I did need to use an explicit save operation though.
However, I am now getting 3 warnings like the following.
Type 'ReferenceWritableKeyPath<MyModel, Optional>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode
The line of code that produced that warning is
`let fetchDescriptor = FetchDescriptor(sortBy: [SortDescriptor(\MyModel.title)])
However, when I flip the switch back to Swift 6, the three warnings go away and I have zero warnings under Swift 6.
Hi! I am seeing some unexpected behavior when attempting to create a Model instance with a variable named updated. I start with a simple Model:
@Model final public class Item {
var timestamp: Int
var updated: Int
public init(timestamp: Int = 1, updated: Int = 1) {
self.timestamp = timestamp
self.updated = updated
}
}
I then attempt to create an item instance:
func main() throws {
let schema = Schema([Item.self])
let configuration = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(
for: schema,
configurations: configuration
)
let modelContext = ModelContext(container)
let item = Item()
print(item.timestamp)
print(item.updated)
}
try main()
The value of item.timestamp is printing as 1 and the value of item.updated is printing as 0.
I have no idea what could be causing that to happen… why would both those values not be printing as 1? Is there some private API that is somehow colliding with the (public) updated variable and causing the item instance to report back with a value of 0? Is there documentation warning engineers that a variable named updated is off-limits and results in undefined behavior?
I can fix that by renaming the variable:
@Model final public class Item {
var timestamp: Int
var updatedTimestamp: Int
public init() {
self.timestamp = 1
self.updatedTimestamp = 1
}
}
I am unblocked on this (because renaming the variable seems to work fine)… but is there any insight on why this might be happening in the first place? I am building from Xcode_16_beta_5. Thanks!
Recently I've been working on a demo project called iLibrary. The main goal was to learn more about CloudKit and SwiftData. After a while I noticed that there were some hangs/freezes when running the app in debug mode.
I first tried this with Xcode 15.4 and iOS 17.5. Here the hang only appears at the beginning, but only for a few seconds. But when I exit debug mode, there are no more hangs.
With Xcode 16 beta 4 and iOS 18 it looks completely different. In this case, the hangs and freezes are always present, whether in debug mode or not. And it's not just at the beginning, it's throughout the app. I'm aware that this is still a beta, but I still find this weird. And when I profile this I see that the main thread gets quite overloaded. Interestingly, my app doesn't have that many operations going on. So I guess something with the sync of SwiftData or my CloudKitManger where I fetch some records from the public database is not running fine.
Lastly, I wanted to delete the iCloud app data. So I went to Settings and tried to delete it, but it didn't work. Is this normal?
Does anyone have any idea what this could be? Or has anyone encountered this problem as well? I'd appreciate any support.
My project: https://github.com/romanindermuehle/iLibrary
On top of unstable CloudKit sync, we've got also extremely unstable sharing/collaboration functionality.
I mean, it's quite impressive how easy it is to enable sharing, but this feature should not be released at this point. It feels like using software in the alpha version.
Let's take NSPersistentCloudKitContainer.share(_:to:) (https://developer.apple.com/documentation/coredata/nspersistentcloudkitcontainer/3746834-share), the documentation says:
Sharing fails if any of the following conditions apply:
Any objects in managedObjects, or those the traversal finds, belong to > an existing share record.
However, it's wrong... if you pass any object from the existing share, it will return the same share... It never fails in this case.
Things are getting even weirder if you experiment a little bit with shares. So let's assume you share a couple of objects:
persistentContainer.share([A, B, C, D], to: nil)
Now you stop sharing those via UICloudSharingController and you want to share again but just C. So you call:
persistentContainer.share([C], to: nil)
and surprise, surprise, you get a new share URL, but you share all previously shared objects (A, B, C, D), not as you would have expected only C...
On top of that, you keep getting some weird errors like:
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2190): <NSCloudKitMirroringDelegate: 0x3029b84b0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringExportRequest: 0x30359f1b0>123123123123' due to error: <CKError 0x3018699b0: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = 12312312312312; container ID = "iCloud.some.id"; partial errors: {
com.apple.coredata.cloudkit.share.123123123123123:__defaultOwner__ = <CKError 0x30186a3d0: "Invalid Arguments" (12/2006); server message = "Only shared zones can be accessed in the shared DB"; op = 12312312312312; uuid = 123123123123>
}>
Even though the only thing I use is
persistentContainer.share
and
UICloudSharingController(share: share, container: cloudKitContainer)
And the cherry on the top, from time to time if you play a little with sharing multiple objects at once, it happens that it randomly wipes out some records from that share...
I don't even know where to start reporting issues and if its worth it, because every ticket will be dismissed anyway because "we need thousands of your logs, we require you to do all the job for us".
My app is using SwiftData with CloudKit integration. Everything at the moment is working fine. I have a struct that saves Data as an optional. This is Data related to an Image. It saves and loads as expected. When I disconnect my phone from wifi or my phone network, the image still loads. I'm assuming that means the Data is being stored locally on the phone as well. Is there a way to display what's stored locally to the user inside the application?
Edit: I've realized that CloudKit is saying the data is too large, but the images are still being saved. Does that mean they're only locally being saved?
Is there any version of UICloudSharingController available on macOS or do we need to handle it manually?
How to manually configure a share and send an invitation from macOS?
Hello!
I apologize in advance if I chose the wrong topic for my question, this is my first time on this forum.
I am a novice developer and I am creating an application. I use Swift + SwiftUI, but I ran into such a problem that I have nowhere to store my data and I do not know how to store it correctly. I know that there is a SwiftData framework that is used to work with data, but I don't understand the documentation.
Please be understanding. How do I start learning SwiftData? What topics should be studied? What is the order of studying topics? Thank you all in advance!
What is the recommended way of intercepting and processing errors?
As far as I know, there are 4 main areas:
iCloud account status - this can be checked and intercepted via notifications
exceptions from fetch/execute/save - it can be a simple do..catch, but what exceptions can we expect here, what should be handled, and how?
there could be some asynchronous issues with synchronization. How should we intercept them and how should they be handled?
issues with iCloud storage - quota exceeded, etc. How to intercept & handle those?
I'm trying to achieve production-ready implementation, but there are many pitfalls and hidden issues that are not well documented. Could you provide some advice on how to handle properly all these situations?
Hello,
I'm using NSPersistentCloudKitContainer. If the user disables iCloud sync for my app in the system settings and opens the app, all records are immediately wiped out, even if there are unsynced changes (like records added offline).
Disabling iCloud sync doesn't even show any warning, so the user may lose all data (if it's not already synced to Cloud).
Is it possible to intercept that the store will be wiped out when the app is launching? I would copy all records to the local storage then to avoid losing data by the user.
Some of my models have many-to-many relationships. For example, when I add a file to a directory, a model is created from that in addition to any relationships it may contain.
I’ve incorporated SwiftData History into my front end and backend projects and it’s able to show me what has been inserted, updated, and even deleted after the file is removed from the directory. Which only returns the identifiers I’ve set to become tombstone values. All working as expected and my client can now sync with the server.
I can add and remove the same file repeatedly and I’m able to retrieve all the transactions.
However if I add another file and then fetch transactions, it crashes at .fetchHistory(_:). The errors say they cannot find the property of a model it has a many-to-many relationship with.
I omitted appending any relationships, but the errors start pointing to properties belonging to the model itself.
I’ve only managed to get this functioning by setting the @Relationship macro to a single model. Previously, I had this macro with its delete rule and inverse on other types. But doing so would crash the same way immediately and wouldn’t let me fetch history at all.
Since it crashes at fetching the history, I’m unable to proceed and the options appear to be limited for what I can do before I fetch them.
Does SwiftData History not work with many-to-many relationships or is this a bug?
I am trying to use the ModelContainer's "delete" function to delete all instances of a model but I'm getting an error related to my relationships:
Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on LeagueSeasonRanking/golfer
I do have a relationship on Golfer, a toMany relationship to LeagueSeasonRanking which is marked with a cascade delete rule... I would expect that to take care of things and cascade along but it seems to not work. Is that a bug?
Hi,
I know how to sort SwiftData records based on one of its properties such as name, but how to sort based on recent updated records ? like in Apple Notes App ?
Kind Regards
I'm just starting to learn iOS app development and I'm currently using SwiftData. The main app is working fine, and now I've added a Widget to use data from the main app. I've already enabled App Groups and want to reference the shared model entities from the main app, but I'm getting an error saying "can't find type in scope." What additional configurations do I need to make in order to properly reference the same entities? I've seen many example codes that have a "Shared" folder, but even after creating one and moving the files into it, I'm still unable to use them properly. I must be missing some configuration, right?
Also, there's another issue: when debugging the Widget, I keep getting the following error. What could be causing this?
SendProcessControlEvent:toPid: encountered an error: Error Domain=com.apple.dt.deviceprocesscontrolservice Code=8 "Failed to show Widget 'XXXX-Widget' error: Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.apple.springboard" failed."
Apparently the @Query property wrapper from SwiftData does not update when data is loaded from CloudKit. The data can be programmatically be accessed but nothing appears in the view.
Steps to reproduce:
Create new Xcode project using the SwiftData storage option.
Provide a default value for the Item Model. That is required so data can be automatically synced by SwiftData.
Enable iCloud -> CloudKit capabilities and choose a container
Enable Background Modes -> Remote notification capability
Add a toolbar button that prints the number of items from @Query like this:
ToolbarItem {
Button {
print(items.count)
} label: {
Label("Count", systemImage: "1.circle")
}
}
Install app on a physical device that can sync to iCloud.
Add some items using the + in the toolbar
Delete app and wait for around a minute
Reinstall app with a debugger attached
Press the 1.circle button in the toolbar. It will print either 0 or the number of items you previously added. When it does not print 0 the data should be visible but it is not. Once you quit and relaunch the app or press the + button again, all of the items appear.
Has anyone else experienced this before? Anything I can do so the data appears / the view reloads once the items are available? I need to update my view once the data has been loaded from iCloud.
I already filed a bug report with id FB14619787.
I wonder why that happens.
When opened on Mac.
Acceptance of files with the '.hwp' extension is applied. But not on ipad
I'd like to know why, where can I get information?
here is the code
<!DOCTYPE html>
<html>
<body>
<h1>The input accept attribute</h1>
<form action="/action_page.php">
<label for="img">Select file:</label>
<input type="file" accept=".pdf, .hwp">
</form>
</body>
</html>
I begin testing my IOS swiftdats Xcode 15 swift 5 on Sonoma and I am able to create my siwftdata tables as well as add records to several of the tables, Then as I proceeded with my te tables disappear and I get this error in the Xcode debug console:
error: Error: Persistent History (6) has to be truncated due to the following entities being removed: (
AppSettings,
Invoice,
Clientele,
Pay,
InvoiceItem,
TrackingArt
)
This app used to work fine and as I was making changes it started behaving in this manner. Beside the code I will supply the entire debug console with the attached file
debugConsole.txt
Here is how I have the swift data containers setup.
import SwiftData
import TipKit
import CloudKit
@main
struct ArtManagerApp: App {
@StateObject private var copyInvoiceDetails = CopyInvoiceDetails()
@StateObject private var copyPaymentDetails = CopyPaymentDetails()
@StateObject private var artTypeSettings = ArtTypeSettings()
@StateObject private var tipManager = TipManager()
// @Query(sort: \ArtPiece.artPieceID, order: .forward) private var artPieces: [ArtPiece]
// @Query(sort: \AppSettings.setID, order: .reverse) private var settingsList: [AppSettings]
var sharedModelContainer: ModelContainer = {
let schema = Schema([
ArtPiece.self, Clientele.self, TrackingArt.self, Invoice.self, InvoiceItem.self, AppSettings.self, Pay.self
])
let modelConfiguration = ModelConfiguration(schema: schema,
isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
.navigationTitle("🎨 Art Manager")
.environmentObject(artTypeSettings)
.environmentObject(copyInvoiceDetails)
.environmentObject(copyPaymentDetails)
.environmentObject(tipManager) // Pass it to the ContentView
.modelContainer(sharedModelContainer)
}
}
}
class TipManager: ObservableObject {
@Published var tips: [ArtManagerTip] = []
init() {
loadTips()
}
func loadTips() {
tips = [ArtManagerTips.search_tip, ArtManagerTips.delete_tip, ArtManagerTips.extendedSearch_tip,
ArtManagerTips.searchPayments_tip, ArtManagerTips.searchArt_tip, ArtManagerTips.librarySearch_tip, ArtManagerTips.artMaintenanceSearch_tip]
}
}
class CopyPaymentDetails: ObservableObject {
@Published var payNumber: Int32 = 0
@Published var payType: String = ""
@Published var payPatronID: Int32 = 0
@Published var payPatronName: String = ""
@Published var payPatronAddress: String = ""
@Published var payPaymentAmount: Double = 0.0
@Published var payDatePayed: Date = Date()
}
class CopyInvoiceDetails: ObservableObject {
@Published var invoiceNumber: Int32 = 0
@Published var invoicePatronName: String = ""
@Published var invoicePatronPO: String = ""
@Published var invoiceDateCreated: Date = Date()
@Published var artPieceIDSaved: [Int32] = []
}
CloudKit sync is very unstable. Sometimes it just stops syncing for no reason, other times it works almost instantly.
The core issue with synchronization is that CoreData relies mostly on two things:
silent push notifications, which are by design unreliable and can be throttled
user interactions, I noticed that the local database is updated most likely periodically and also based on some app events like entering the foreground.
Unfortunately, there is no SDK function that allows us to force sync with CloudKit, which basically prevents us from providing some features to recover if a user encounters problems.
After thousands of tests, I finally discovered what was wrong and how to make the synchronization stable. Basically, I noticed that at some point CoreData decides that it won't synchronize data unless you deactivate and activate the application, which is crazy. It's getting even worse if we talk about extensions like the keyboard extension on iOS. The same happens on all platforms.
Therefore, knowing that I implemented a trick that happened to work perfectly. The workaround requires to periodically sending an event pretending that the app is going foreground.
macOS:
var cancellable = Set<AnyCancellable>()
// ...
Timer.publish(every: 20.0, on: RunLoop.main, in: .common)
.autoconnect()
.sink { _ in
NotificationCenter.default.post(.init(name: NSApplication.willBecomeActiveNotification))
}
.store(in: &cancellable)
iOS:
var cancellable = Set<AnyCancellable>()
// ...
Timer.publish(every: 20.0, on: RunLoop.main, in: .common)
.autoconnect()
.sink { _ in
NotificationCenter.default.post(.init(name: UIApplication.didBecomeActiveNotification))
}
.store(in: &cancellable)
After that, everything works perfectly. Pitty that the solution mostly meant for enterprise is so unstable and there is not even a single SDK function to recover from that (force sync).
Any plans to fix CoreData+CloudKit? I also created a ticket: #FB14531806.
This just started happening when installing my app on my phone and ipad. It still seems to work and the errors go away on the second installation, but it doesn't strike me as good.
The app has not been released yet.
When I remove the AppGroup, the error disappears. But I have a widget, so I need the AppGroup.
I've cleaned the build, deleted derived files, and rebooted many times.
I've deleted the app on the device and rebooted the device many times.
I've deleted the AppGroup in iCloud and then recreated it. I was really hoping that would work, but nope. I've created a new App Group and that didn't make a difference either.
So I'm stumped. Any thoughts on how to fix this?
thanks
CoreData: error: Failed to stat path '/private/var/mobile/Containers/Shared/AppGroup/2602E28B-089C-4011-BA09-19D11183E4F7/Library/Application Support/default.store', errno 2 / No such file or directory.
CoreData: error: Executing as effective user 501
CoreData: error: Failed to statfs file; errno 2 / No such file or directory.
CoreData: error: Logging status information for directory path: /private/var/mobile/Containers/Shared/AppGroup/2602E28B-089C-4011-BA09-19D11183E4F7/Library/Application Support
CoreData: error: Executing as effective user 501
....
error: URL: file:///private/var/mobile/Containers/Shared/AppGroup/2602E28B-089C-4011-BA09-19D11183E4F7/Library/Application%20Support/default.store
error: <NSPersistentStoreCoordinator: 0x300a3e610>: Attempting recovery from error encountered during addPersistentStore: 0x302f5f510 Error Domain=NSCocoaErrorDomain Code=512 "The file couldn’t be saved." UserInfo={reason=Failed to create file; code = 2}
error: During recovery, parent directory path reported as missing
error: Recovery attempt while adding <NSPersistentStoreDescription: 0x302f5f510> (type: SQLite, url: file:///private/var/mobile/Containers/Shared/AppGroup/2602E28B-089C-4011-BA09-19D11183E4F7/Library/Application%20Support/default.store) was successful!
I am able to fetch CloudKit records from my MacOS command line tool/daemon.
However, I would like CloudKit to notify my daemon whenever CKRecords were altered so I would not have to poll periodically.
In CloudKit console I see that my app successfully created CloudKit subscription, but the part that confuses me is where in my app do I define callback function that gets called whenever CloudKit attempted to notify my app of CloudKit changes?
My first question - do I need to define callback in my implementation of UNUserNotificationCenterDelegate? NSApplicationDelegate? Something else?
My second question, would CKSyncEngine work from command line application?