iCloud & Data

RSS for tag

Learn how to integrate your app with iCloud and data frameworks for effective data storage

CloudKit Documentation

Post

Replies

Boosts

Views

Activity

How to store Public Data in ICloud
I have been working on an ios application which I decided to use the new SwiftData architecture, and I now have realized that SwiftData does not support public or shared databases using SwiftData. I am a new and upcoming Swift developer, who has been self learning the Apple Swift technology. I just learned in this forum that Swift Data does not support Public and Shared Data and I also understand that no plans that have been announced to addressed this feature in the IOS 18 release time frame. The use case for my application is to implement a social type application, something like applications including X, facebook, etc. These type of applications appear to use Public, Shared and Private data in various existing Apple application. I would like to complete an application using Swift using ICloud, but I must assume that these current social applications are using other technologies. I am assuming you can do this in Core Data, but my understanding is Apple is asking that we use Swift Data to replace core data. I also am assuming that Swift data is built on core data technology layers. So ... to me it seems hopeful, somehow, to accomplish this using IOS 17 and follow the recommend Swift Data Path. What are my options for completing these data objectives in IOS? I hope I am addressing these questions in the proper and best forum? Much thanks for any suggestions.
3
1
476
May ’24
Failed to create public DB CloudKit subscription in production
I'm attempting to save a CKQuerySubscription in production, in the public database, but I'm seeing the following error: Failed to create CloudKit subscription for Encounter: <CKError 0x3038f66a0: "Invalid Arguments" (12/2006); server message = "attempting to create a subscription in a production container"; op = 093C69242BCC1B0A; uuid = D6E49665-6B8A-4F16-BBD8-B188A4E71F70; container ID = "iCloud.com..."> This is the query’s predicate: NSPredicate(format: "users CONTAINS %@", user.recordID), and the same subscription works perfectly fine in the development CloudKit environment. I have a queryable index on the users field in both environments. Also, I have saved a TRUEPREDICATE CKQuerySubscription in production, and that works perfectly. Does anyone know what I could be missing here?
1
0
272
Jun ’24
swiftUI apps with SwiftData and CloudKit crashes on iOS but works on MacOS
sample code let modelConfiguration = ModelConfiguration() // 1. create mom guard let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Attachment.self]) else { fatalError("====> makeManagedObjectModel error") } // 2. create description with config url and setting let description = NSPersistentStoreDescription(url: modelConfiguration.url); description.shouldAddStoreAsynchronously = false; container = NSPersistentCloudKitContainer(name: "swiftDataCloudTest", managedObjectModel: mom); container.persistentStoreDescriptions = [description] // 3. get modelContainer let modelContainer = try! ModelContainer(for: Attachment.self, configurations: self.modelConfiguration) this code works fine on MacOS(14.4.1) and previous iOS 17.x.(iOS 17.2 is OK) but on iOS 17.5, the app crashes with message A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Unable to find a configuration named 'default' in the specified managed object model how can I fix these?
4
0
324
Jun ’24
Sign in with Apple - problem when account is deleted
I'm currently working on a Swift app whose data storage and authentication part is managed by Firebase. I would like to offer my users the possibility of using their Apple account for account creation. To do this I added Apple as a “Connection Provider” in the Firebase console settings. 
 

 This part works without problem, when the user clicks on the “Sign in with Apple” button a popup appears asking if they agree to share this information (first and last name / email address) for account creation.

 After entering the password, the user is authenticated and their account is created on Firebase.
  If I go to the iPhone settings in the Connection and Security section > Sign in with Apple, I can see my app in the list.
  Now my problem is at the time of deleting the user's account. When the account is deleted it no longer exists in Firebase as we expected.
  An email is also sent by Apple to warn that the application has revoked the account that had been created with “Sign in with Apple”.
 And the application no longer appears in the list of applications in the Connection and Security > Connection with Apple from iPhone section. However, when I click on the “Sign in with Apple” button again, I don’t see the window that asks me if I want to share my connection information. The app behaves as if I was simply logged out but when I enter my iCloud password I am logged in except in reality it is a new account. 
When I look in Firebase I have a new id for my user.
  In addition, the user is not really connected to the application since certain views behave as if the user session was empty. The only way is to erase the emulator and make a new build. I need help finding what's not working in my current code because I've been going around in circles for several days and I really don't understand what's going on. Here my entire AuthentificationViewModel: AuthentificationViewModel.txt
1
0
300
May ’24
use of @Model macro from SwiftData causes project build to fail
Target tvOS 17.4 macOS Version 14.5 Xcode Version 15.4 (15F31d) I am working on integrating SwiftData (not migrating from CoreData) into an app in active development for tvOS, and I cannot get the project to compile whenever the @Model macro is introduced. I've traced every error back to the code generated by the @Model, and commenting it out removes the errors. I am able to use @Model on a fresh project, but any attempt to import SwiftData results in the build failing with the following errors: /var/folders/t5/c9qp7_4j19x9s3p3z26kn6v80000gn/T/swift-generated-sources/@__swiftmacro_9AeolusKit11DeviceModel0D0fMe_.swift:1:1 Type 'DeviceModel' does not conform to protocol 'Observable' /var/folders/t5/c9qp7_4j19x9s3p3z26kn6v80000gn/T/swift-generated-sources/@__swiftmacro_9AeolusKit11DeviceModelC2id18_PersistedPropertyfMa_.swift:4:9 Member 'setValue' cannot be used on value of type 'any BackingData<DeviceModel>'; consider using a generic constraint instead /var/folders/t5/c9qp7_4j19x9s3p3z26kn6v80000gn/T/swift-generated-sources/@__swiftmacro_9AeolusKit11DeviceModel0D0fMe_.swift:4:36 'Observable' is not a member type of struct 'AeolusKit.Observation' /var/folders/t5/c9qp7_4j19x9s3p3z26kn6v80000gn/T/swift-generated-sources/@__swiftmacro_9AeolusKit11DeviceModelC2id18_PersistedPropertyfMa_.swift:4:50 Cannot convert value of type 'String' to expected argument type 'PersistentIdentifier' /var/folders/t5/c9qp7_4j19x9s3p3z26kn6v80000gn/T/swift-generated-sources/@__swiftmacro_9AeolusKit11DeviceModelC2id18_PersistedPropertyfMa_.swift:8:54 Cannot infer key path type from context; consider explicitly specifying a root type /var/folders/t5/c9qp7_4j19x9s3p3z26kn6v80000gn/T/swift-generated-sources/@__swiftmacro_9AeolusKit11DeviceModelC2id18_PersistedPropertyfMa_.swift:12:64 Cannot infer key path type from context; consider explicitly specifying a root type /var/folders/t5/c9qp7_4j19x9s3p3z26kn6v80000gn/T/swift-generated-sources/@__swiftmacro_9AeolusKit11DeviceModel0D0fMm_.swift:25:50 Type 'Observation' has no member 'ObservationRegistrar' the code in question causing the error: import Foundation import SwiftData @Model public final class DeviceModel { @Attribute(.unique) public var id: String init(id: String) { self.id = id } } I've already done the following: clean the project erase the contents of the derived directory restart xcode restart my mac. I want to emphasize, I do not believe it is my code causing this issue, as commenting out the @Model result's in a perfectly normal build with no warnings or errors Any help is appreciated
2
0
262
Jun ’24
Setting up Query in init causes app to freeze
I'm trying to filter results to get all characters that are associated with a story. When navigating to the view it filters as it should, but as soon as you select the Add Character option, the app just freezes. I've found that if I comment out the Query line in the init, and filter out as part of the foreach I don't get the freeze. Can anyone advise how I should be doing these predicates as it seems init isn't the best place to do it The views code is import SwiftUI import SwiftData struct CharacterListView: View { let story : Story @Query(sort: \Character.name, order: .forward) private var characters: [Character] var body: some View { List { ForEach(characters) { char in CharacterListCellView(char: char) } } .toolbar { ToolbarItem { NavigationLink(destination: CharacterAddView(story: story)) { Label("Add Character", systemImage: "plus") } } } .navigationBarTitle("Characters", displayMode: .inline) } init(story: Story) { self.story = story let id = story.persistentModelID let predicate = #Predicate<Character> { char in char.story?.persistentModelID == id } _characters = Query(filter: predicate, sort: [SortDescriptor(\.name)] ) } } I've narrowed it down to a line in the AddCharacterView file struct CharacterAddView: View { @Environment(\.modelContext) private var modelContext @Environment(\.dismiss) var dismiss let story : Story // Character details @State private var characterName: String = "" // Images @State private var showImageMenu = false; @State private var isShowPhotoLibrary = false @State private var isShowCamera = false //@State private var image = UIImage() <-- This line @State private var imageChanged = false @State private var isSaving : Bool = false var body: some View { } } If I do either of the below it works If I comment out the UIImage variable then I don't get the freeze, but I can't update the image variable If I comment out the query in init, then it works but doesn't filter and I have to do it as part of the foreach
0
0
180
May ’24
Unable to Add for Review
I have changes the screenshot and process for app review but it doesn't work. Unable to Add for Review The items below are required to start the review process: There are still screenshot uploads in progress. its benn 1 hour please fix it
0
0
91
May ’24
CloudKit JS database subscription
Hi, it is possible to accept an invitation to a zone in a shared db using cloudkit js, but can you subscribe to receive change notifications? It doesn't look like you can create a database subscription (and zone or query types don't seem appropriate for shared databases). Does that mean you can't get notified and you have to keep polling the cloudkit container for changes? If so, why such a limitation? Thanks
0
0
179
May ’24
The scammers are able to emulate Macbook M1/M2/M3 devices and steal access via lock to icloud
I am a simple mac seller ,i buy broken laptops from people and repair them to sell so one day one my customer asked to show him video of 4 my laptops after he got only video all became iCloud LOCK Summary - my case numbers are 102302104385 + Case Number: 102309395011 my story is simple the customer asked me about video of the Macbook , because as he told me  , he was need a confirmation about how are laptops are looks like   i do not see any suspicious action here  , customer just want me to show him the laptop like online   So i did it - just send him video - and that is all  then he asked to send video about 3 more Macbooks after it he asked me to Use Erase All Content and Settings so i was sure that there will be no problem  - because i just replaced the motherboard    two weeks ago - so what can be wrong    so when i did it - the Macbook asked if the apple server let him activation  and it was refused   Somehow person who get the video about laptop did a copy of a signal that apple laptop send to apple activation server  and connected  it to his apple id  and after it enabled FMI FMD  - but all time my laptops was turned off But i have video confirmation in my cases that all laptops are without any Apple Id and have new and fresh mac os so after it i was not able to pass the activation because i was scammed and unknown person connected 4 my laptops to unknown account , so after that i was not able to pass the activation  so in fact they are all bricked now   he asked me to pay 1000 $ i told apple about it and they  answer me that it is just my fairy tail and it is not possible   i told them that there is a hole in security and identification of apple devices during enabling FMI FMD  but as i see they do not care - i think it must about 100 same cases  or 1000 - maybe after it they will take care about it  so now i wonder if there any more victims who have the same problem  ? or check here at youtube ServisTT also i and apple support did full apple diagnostic about all devices - i want apple to compare mac addresses and other mac information with the signal that was emulated with the scammer to prove my words - because the scammer was at different location and his emulation device or software was different between my original one macbook Steps to reproduce https://www.youtube.com/watch?v=58AgEcZvrYg&t=98s or check here at youtube ServisTT Expected results i want apple to compare mac addresses and other mac information with the signal that was emulated with the scammer to prove my words - because the scammer was at different location and his emulation device was different between my original one also if you find out that he used Hardware UUID - so why not to mask it or hide or make enable to see only with the password 
 Actual results NO ONE TRUST ME AND NO ONE WANT TO HELP ME
0
0
410
May ’24
Xcode - Sqlite versions
In Xcode (Mac OS Catalina), when trying to create an application to access a database, I receive syntax errors, resulting from the installed version of SQlite (below 3.30) does not allowing generation of virtual columns. After updating to 3.46 the version installed on system, this does not occur if I execute such queries directly in SQlite, via Terminal. How do I get Xcode to access and use the system updated version ? Thanks in advance
2
0
206
May ’24
Access Core Data ModelContainer with SwiftData
I have an app that uses CoreData and I want to migrate to SwiftData. After following the Migrate to SwiftData session, I only need to point to my old Core Data file to read the old data and convert it to the new SwiftData format. My question is how do I do this? Maybe worth mentioning is that my NSPersistentContainer(name: "Model") is different to my app name. Possible Solution? According to a Tweet by Donny Wals this is done this way: By default a SwiftData ModelContainer will create its underlying storage in a file called default.store. If you want to change this so you can use an existing Core Data SQLite file, you can point your container to that file instead: // point to your old sqlite file let url = URL.applicationSupportDirectory.appending(path: "Model.sqlite") let config = ModelConfiguration(url: url) modelContainer = try ModelContainer(for: [ Movie.self ], config) My Tested Code @main struct SwiftData_TestApp: App { let url = URL.applicationSupportDirectory.appending(path: "Model.sqlite") let config = ModelConfiguration(url: url) let modelContainer = try ModelContainer(for: [ Item.self ], config) var body: some Scene { WindowGroup { ContentView() } .modelContainer(modelContainer) } } The problem here is that I don’t get it to work in the main app struct. When using this the way described in Dive deeper into SwiftData (at 6:58) I only get the error: Cannot use instance member 'url' within property initializer; property initializers run before 'self' is available PS: There seems to be an issue with this WWDC session method anyway – see this post.
2
0
1.9k
Jun ’23
Added new field to swiftdata model, now crashes
I had a simple class called Entry with one field (timestamp: Date) and I tried to add a new field without having to uninstall the app , so I would not crash. I tried implementing the MigrationPlan stuff but I do not know if I have to manually add a value to the new field or how exactly it works. Here is my code. When I use the EntrySchemaV0 it works fine but if I try to use the V1 it crashes. (could not fetch ModelContainer) I also tried it with a custom migration stage. Crashes with error (SwiftData/BackingData.swift:432: Fatal error: Expected only Arrays for Relationships - String) import Foundation import SwiftData enum EntrySchemaV0: VersionedSchema { static var versionIdentifier = Schema.Version(0, 1, 0) static var models: [any PersistentModel.Type] { [Entry.self] } @Model final class Entry { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } } enum EntrySchemaV1: VersionedSchema { static var versionIdentifier = Schema.Version(0, 2, 0) static var models: [any PersistentModel.Type] { [Entry.self] } @Model final class Entry { var name: String var timestamp: Date init(name: String = "", timestamp: Date = .now) { self.name = name self.timestamp = timestamp } } } enum EntryMigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [EntrySchemaV0.self, EntrySchemaV1.self] } static var stages: [MigrationStage] { [migrateV0toV1] } static let migrateV0toV1 = MigrationStage.lightweight( fromVersion: EntrySchemaV0.self, toVersion: EntrySchemaV1.self ) }
3
3
944
Oct ’23
SwiftData doesn't parse my object correctly
Hello, im trying to parse a JSON Request into a Swift Data Model. The specific bug happens with the nutriscore. It works perfectly fine if I do my request and Decode or Encode the Model directly. But when im trying to add it to the Database the field is empty. Somehow when im iterating through each product (my model) and console log it, it works. But only if there is one product in my database. sometimes when im adding another product, it somehow deletes(?) all nutriscores and the console log prints "nil" for all products. even for the product it worked before. This right here is the way I insert into my database which should be perfectly fine. And the printing works also perfectly fine and it always displays the correct nutriscore func dataScanner(_ dataScanner: DataScannerViewController, didAdd addedItems: [RecognizedItem], allItems: [RecognizedItem]) { for item in addedItems { if case let .barcode(barcode) = item { performAPIRequest(with: barcode.payloadStringValue!) { result in switch result { case .success(let product): ... var descriptor: FetchDescriptor<Product> { var descriptor = FetchDescriptor<Product>( predicate: #Predicate { $0.code == product.code } ) descriptor.fetchLimit = 1 return descriptor } var products: [Product] = [] products = try! self.parent.context.fetch(descriptor) print(product.nutriscore ?? "no nutri"); //WORKS PERFECTLY FINE!! if let existingProduct = products.first { existingProduct.amount! += 1 existingProduct.lastScannedAt = Date() } else { self.parent.context.insert(product) } self.processMeals() case .failure(let error): print("Error: \(error)") } } } } } This has to be a SwiftData Bug, or why doesn't it work
1
0
261
May ’24
Xcode NSMetaDataQuery error on device running IOS 17.5 - [ERROR] couldn't fetch remote operation IDs
Xcode 15.4 running on various IOS simulators and hardware devices from IOS 14.5 to 17.5. Part of my code presents a backup/restore page to the user which uses NSMetaDataQuery to update the GUI for files being uploaded or downloaded in iCloud. On every device I run the code everything works as expected EXCEPT one which is an iPhone 11 running IOS 17.5 (as of yesterday 17.5.1); there I get the following error once I start the query: [ERROR] couldn't fetch remote operation IDs: NSError: Cocoa 257 "The file couldn’t be opened because you don’t have permission to view it." "Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)"" Due to this error I am getting no query updates and thus unable to display whether the file needs to upload, download or is synchronised. I am not initiating any upload or download of the backup file since it is placed in the ubiquitous container and I leave the up/download of the file over to IOS; all I do with the query is monitor the status of the file and take appropriate action to show the user the percentage of up/downloaded file. As said before it is only the one device causing me headaches so I don't know whether it has anything to do with IOS 17.5 that Apple have made changes that I am unaware of. I have access to an iPhone and an iPad running some version of IOS 16 and it's performing flawlessly. I have no other IOS17+ device to test on. The code runs very well on any 17.5 simulator, but we all know there are always some differences running code on a Device vs Simulator. Running 'startAccessingSecurityScopedResource()' which has been suggested by some returns 'true' on the simulator and 'false' on a device, but even then all devices work except one; so that does not seem to be the solution. Changing the query predicate has not helped either. How do I drill down to find the culprit - I'm at my wits' end. My very simple query initializer, startup & observers: (Please note, the code shown here is what's left after commenting out everything else. This was done to show that the problem really DOES lie with the Query) query = NSMetadataQuery.init() query.operationQueue = .main query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope] query.predicate = NSPredicate(format: "%K LIKE %@", NSMetadataItemFSNameKey, fileUrl.lastPathComponent) query.operationQueue?.addOperation({ [weak self] in self?.query.start() self?.query.enableUpdates() }) } func addNotificationObservers() { NotificationCenter.default.addObserver( self, selector: #selector(queryDidStart(_:)), name: .NSMetadataQueryDidStartGathering, object: query) NotificationCenter.default.addObserver( self, selector: #selector(queryGathering(_:)), name: .NSMetadataQueryGatheringProgress, object: query) NotificationCenter.default.addObserver( self, selector: #selector(queryDidUpdate(_:)), name: .NSMetadataQueryDidUpdate, object: query) NotificationCenter.default.addObserver( self, selector: #selector(queryDidFinishGathering(_:)), name: .NSMetadataQueryDidFinishGathering, object: query) }
3
0
329
May ’24
SwiftData: Application crash when trying to save (and fetch) a Model with unique attribute a second time
The context is to create a model instance in SwitfData and return it. This model as a unique attribute (defined by @Attribute(.unique)). The application runs fine the first time but on the second run, it fails with EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP). What the reason behind this crash? Here is my sample application to duplicate the issue. The issue is reproducible on MacOS and iOS: import SwiftUI import SwiftData @available(iOS 17, *) @available(macOS 11, *) @Model public final class MyModel : CustomStringConvertible { @Attribute(.unique) var uuid: UUID init(uuid: UUID) throws { self.uuid = uuid } public var description: String { return self.uuid.uuidString } } @available(iOS 17, *) @available(macOS 11, *) @ModelActor public actor LocalDatabaseService { public static let shared = LocalDatabaseService() let schema = Schema([MyModel.self]) public init() { self.modelContainer = try! ModelContainer(for: self.schema) let context = ModelContext(modelContainer) self.modelExecutor = DefaultSerialModelExecutor(modelContext: context) } public func createMyModel(uuid: UUID) throws -> MyModel { let myModel = try MyModel(uuid: uuid) let modelContext = self.modelContext modelContext.insert(myModel) try modelContext.save() return myModel } } struct ContentView: View { var body: some View { Task { let id = UUID(uuidString: "9C66CA5B-D91C-480F-B02C-2D14EEB49902")! let myModel = try await LocalDatabaseService.shared.createMyModel(uuid: id) print("myModel:\(myModel)") print("DONE") } return VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } #Preview { return ContentView() } Note: a workaround is to returned the fetched model instance return try self.getMyModel(uuid: uuid): func getMyModel(uuid: UUID) throws -> MyModel { let fetchDescriptor = FetchDescriptor<MyModel>(predicate: #Predicate { $0.uuid == uuid }) let serverList = try modelContext.fetch(fetchDescriptor) if !serverList.isEmpty { if let first = serverList.first { return first } } fatalError("Could not find MyModel with uuid \(uuid)") } ... but it does not explain the crash.
1
0
280
May ’24
Memory usage unstoppably increasing when updating SwiftData Object from Timer
For a kind of podcast player I need to periodically update a swiftData object to keep track of the listening progress. (Happy to hear if there are better ways) I need to do this in many places in my app so I wanted to extract the modelContext into a Singleton so I can write a global function that starts the timer. In doing so I stumbled upon a problem: The memory used by my app is steadily increasing and the device is turning hot. @Observable class Helper { static let shared = Helper() var modelContext: ModelContext? } @main struct SingletontestApp: App { let modelContainer: ModelContainer init() { do { modelContainer = try ModelContainer( for: Item.self, Item.self ) } catch { fatalError("Could not initialize ModelContainer") } Helper.shared.modelContext = modelContainer.mainContext } var body: some Scene { WindowGroup { ContentView() } .modelContainer(modelContainer) } } struct ContentView: View { @Query private var items: [Item] var body: some View { NavigationSplitView { List { ForEach(items) { item in Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard)) } } .toolbar { ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } ToolbarItem { Button(action: updateItemPeriodically) { Label("Change random", systemImage: "dice") } } } } detail: { Text("Select an item") } } func addItem() { withAnimation { let newItem = Item(timestamp: Date()) Helper.shared.modelContext!.insert(newItem) } } @MainActor func updateItemPeriodically() { // Doesn't matter if run as global or local func let descriptor = FetchDescriptor<Item>(sortBy: [SortDescriptor(\.timestamp)]) let results = (try? Helper.shared.modelContext?.fetch(descriptor)) ?? [] let element = results.randomElement() let timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { timer in // Smaller time intervals worsen the problem element?.timestamp = Date.now } } } Calling save() manually or automatically in the timer does not have any effect. I am not sure about my general way of keeping track of listening process so if you think there is a better way, feel free to correct me. Thanks for your help
3
0
303
May ’24
Can SwiftData @Model with .externalStorage be used with CloudKit?
Hi, I'm about to adopt .externalStorage but I will also use CloudKit in the near future. I did not find any reference that list of requirements for SwiftData models to be used with CloudKit, only for Core Data models. It seems those Core Data requirements (like no-unique) apply to SwiftData as well. However I did not find any info on this: Can @Attribute(.externalStorage) be used when I want to sync my model with CloudKit?
2
0
264
May ’24
Make my SwiftData code concurrency proof (sendable model, singleton)
Here is my current code: @Model final public class ServerModel { @Attribute(.unique) var serverUrl: URL init(serverUrl: URL) { self.serverUrl = serverUrl } } @ModelActor public actor MyDatabaseService { public static var shared = MyDatabaseService() public init() { self.modelContainer = try! ModelContainer(for: ServerModel.self) let context = ModelContext(modelContainer) self.modelExecutor = DefaultSerialModelExecutor(modelContext: context) } public func listServers() throws -> [ServerModel] { let descriptor = FetchDescriptor<ServerModel>() return try modelContext.fetch(descriptor) } } When try to call try await MyDatabaseService.shared.listServers() There are two problems: ServerModel is not Sendable "Reference to static property 'shared' is not concurrency-safe because it involves shared mutable state; this is an error in Swift 6" For the first one, I can solve it by doing: public struct Server { let serverUrl: URL; } @Model final public class ServerModel { @Attribute(.unique) var serverUrl: URL init(serverUrl: URL) { self.serverUrl = serverUrl } func getSendable() -> Server { return Server(serverUrl: self.serverUrl) } } @ModelActor public actor MyDatabaseService { (...) public func listServers() throws -> [Server] { let descriptor = FetchDescriptor<ServerModel>() return try modelContext.fetch(descriptor).map { $0.getSendable() } } } I am wondering if there is a smarter solution to this first issue. SwiftData already require to define the model with basic/codable types, so if there was a magic way to get a sendable from the model. I try to make my model 'Codable' but 'Codable' is not compatible with 'Sendable'. For my second issue, the singleton issue. I do not really know how to fix it.
1
0
277
May ’24
Is there a way to search in SwitData optional to many relationships?
Done this model: @Model public final class Category: Codable { var nom: String = "" @Relationship(deleteRule: .cascade, inverse: \Property.category) var properties: [Property]? } How to create #predicate to search text in like… let predicate = #Predicate<Category> { category in searchText.isEmpty || category.nom.localizedStandardContains(searchText) || category.properties.contains { $0.nom.localizedStandardContains(searchText) } } without this error: SQLCore dispatchRequest: exception handling request: <NSSQLCountRequestContext: 0x6000038dc620>, to-many key not allowed here with userInfo of (null)
0
0
243
May ’24