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

error: CoreData+CloudKit: Never successfully initialized and cannot execute request - incomprehensible archive
anyone getting the following error with CloudKit+CoreData on iOS16 RC? delete/resintall app, delete user CloudKit data and reset of environment don't fix. [error] error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2044): <NSCloudKitMirroringDelegate: 0x2816f89a0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x283abfa00> 41E6B8D6-08C7-4C73-A718-71291DFA67E4' due to error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)}
3
0
1.2k
Sep ’22
Restart sync when using NSPersistentCloudKitContainer
It's 2024, and it still seems like the only sure way to cleanly restart cloud sync on an app using NSPersistentCloudKitContainer is to uninstall and reinstall the app. No need to describe how bad that solution is... Am I missing something? Is there a better way to safely trigger such a restart of the sync (even if it means losing unsaved data and overwriting with what's in the cloud - which is what a reinstall does anyway)?
2
0
286
May ’24
Writing to Production using an app not on TestFlight / AppStore
Is this possible? Here's what I'm trying: I'm making an app that reads from a CloudKit database. That's working fine. I made a second "admin" type app to update the database. But, of course, I don't intend to release the admin app to the public. So it was all working fine while testing in the development environment, but now that my public app is in TestFlight, and I have updated the necessary stuff that should allow me to write to production, but every attempt successfully writes to development, not production. I'm wondering if I submitted my admin app to TestFlight if it would work then. But that doesn't seem like a long term solution, since I think I would have to re-upload every 90 days... just doesn't seem ideal or correct. Do I HAVE to write the admin functionality in to the public app and hide it? What are better ways I could write to production other than manually through the console? Thanks everyone!
1
0
178
2w
SwiftData ModelContext Fetch Crashing
I'm currently using Xcode 16 Beta (16A5171c) and I'm getting a crash whenever I attempt to fetch using my ModelContext in my SwiftUI video using the environment I'm getting a crash specifically on iOS 18 simulators. I've opened up a feedback FB13831520 but it's worth noting that I can run the code I'll explain in detail below on iOS 17+ simulator and devices just fine. I'm getting the following crash: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The specified URI is not a valid Core Data URI: x-coredata:///MyApp/XXXXX-XXXXX-XXXX-XXXX-XXXXXXXXXXXX' It's almost as if on iOS18 SwiftData is unable to find the file on the simulator to perform CRUD operations. All I'm doing in my project is simply fetching data using the modelContext. func contains(_ model: MyModel, in context: ModelContext) -> Bool { let objId = palette.persistentModelID let fetchDesc = FetchDescriptor<MyModel>(predicate: #Predicate { $0.persistentModelID == objId }) let itemCount = try? context.fetchCount(fetchDesc) return itemCount != 0 }
4
4
414
Jun ’24
Using Core Data with the Swift 6 language mode
I'm starting to work on updating my code for Swift 6. I have a number of pieces of code that look like this: private func updateModel() async throws { try await context.perform { [weak self] in // do some work } } After turning on strict concurrency checking, I get warnings on blocks like that saying "Sending 'self.context' risks causing data races; this is an error in the Swift 6 language mode." What's the best way for me to update this Core Data code to work with Swift 6?
4
1
493
Jun ’24
SwiftData crash: PersistentModel.keyPathToString(keypath:)
I'm distributing an iOS (17.4+) and visionOS (1.2+) app via TestFlight that's using SwiftData. The most common crash by far is from SwiftData when deleting models from a context using a predicate (first snippet below), but so far I've been unable to reproduce it myself locally (second snippet below). I'm using SwiftData outside of SwiftUI views, via my own wrapper, and converting between my app models and SwiftData models. Does anyone have any ideas how I could potentially narrow this issue down (or reproduce), or know of any similar issues? Thanks! — Seb do { try context.transaction { context in let predicate = #Predicate<PersistedFeed> { $0.id == id } do { try context.delete(model: PersistedFeed.self, where: predicate) } catch { // .. Omitted for brevity } } } catch { // .. Omitted for brevity } Crash: Thread 0 Crashed: 0 libswiftCore.dylib 0x000000018dd558c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 SwiftData 0x000000022f7f323c static PersistentModel.keyPathToString(keypath:) + 1496 (DataUtilities.swift:0) 2 SwiftData 0x000000022f83312c PredicateExpressions.KeyPath.convert(state:) + 492 (FetchDescriptor.swift:394) 3 SwiftData 0x000000022f834a24 protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.KeyPath<A, B> + 16 (<compiler-generated>:0) 4 SwiftData 0x000000022f830a70 PredicateExpression.convertToExpressionOrPredicate(state:) + 724 (FetchDescriptor.swift:203) 5 SwiftData 0x000000022f831874 PredicateExpression.convertToExpression(state:) + 36 (FetchDescriptor.swift:217) 6 SwiftData 0x000000022f83b6c8 PredicateExpressions.Equal.convert(state:) + 328 7 SwiftData 0x000000022f8360ec protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.Equal<A, B> + 64 (<compiler-generated>:0) 8 SwiftData 0x000000022f830a70 PredicateExpression.convertToExpressionOrPredicate(state:) + 724 (FetchDescriptor.swift:203) 9 SwiftData 0x000000022f82fd60 PredicateExpression.convertToPredicate(state:) + 28 (FetchDescriptor.swift:224) 10 SwiftData 0x000000022f82edb4 nsPredicate<A>(for:) + 956 (FetchDescriptor.swift:88) 11 SwiftData 0x000000022f807c2c ModelContext.delete<A>(model:where:includeSubclasses:) + 596 (ModelContext.swift:1846) 12 SwiftData 0x000000022f81994c dispatch thunk of ModelContext.delete<A>(model:where:includeSubclasses:) + 56
0
0
175
2w
CloudKit user 'throttling'
Hi, I have some small amount of users who are receiving a lot of "throttling" error messages from CloudKit when they try to upload / download data from CloudKit. I can see this from the user reports as well as the CloudKit dashboard. It's erratic, unpredictable, and is causing all sorts of bad experience in my app. I would like to understand this more: what causes a particular user to 'throttle' vs others, and what can they do to avoid it? as an e.g if we are uploading 4000 records, having split them up into a 100 CKModifyRecordsOperations with 400 records each ... would that result in some operations getting 'throttled' in the middle of the upload? Would all the operations receive the 'throttled' error message, or only some operations? if I replay all the operations after the recommended timeout, could they also get a 'throttle' response? how do I reproduce something like this in the development environment? With my testing and development so far, I haven't run into such an issue myself. Would love to hear some insight and suggestions about how to handle this.
2
0
234
2w
SwiftData via CloudKit Only Syncing Upon Relaunch
Hello I'm a new developer and am learning the ropes. I have an app that I'm testing and seem to have run into a bug. The data is syncing from one device to another, however it takes closing the app on the Mac or force closing the app on iOS/iPadOS to get the app to reflect the new data. Is there specific code I code share to help solve this issue or any suggestions that someone may have? Thank you ahead of time for your assistance. import SwiftData @main struct ApplicantProcessorApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([ Applicant.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() } .modelContainer(sharedModelContainer) } } struct ContentView: View { var body: some View { FilteredApplicantListView() } } #Preview { ContentView() .modelContainer(SampleData.shared.modelContainer) } struct FilteredApplicantListView: View { @State private var searchText = "" var body: some View { NavigationSplitView { ApplicantListView(applicantFilter: searchText) .searchable(text: $searchText, prompt: "Enter Name, Email, or Phone Number") .autocorrectionDisabled(true) } detail: { } } } import SwiftData struct ApplicantListView: View { @Environment(\.modelContext) private var modelContext @Query private var applicants: [Applicant] @State private var newApplicant: Applicant? init(applicantFilter: String = "") { // Filters } var body: some View { Group { if !applicants.isEmpty { List { ForEach(applicants) { applicant in NavigationLink { ApplicantView(applicant: applicant) } label: { HStack { VStack { HStack { Text(applicant.name) Spacer() } HStack { Text(applicant.phoneNumber) .font(.caption) Spacer() } HStack { Text(applicant.email) .font(.caption) Spacer() } HStack { Text("Expires: \(formattedDate(applicant.expirationDate))") .font(.caption) Spacer() } } if applicant.applicationStatus == ApplicationStatus.approved { Image(systemName: "checkmark.circle") .foregroundStyle(.green) .font(.title) } else if applicant.applicationStatus == ApplicationStatus.declined { Image(systemName: "xmark.circle") .foregroundStyle(.red) .font(.title) } else if applicant.applicationStatus == ApplicationStatus.inProgress { Image(systemName: "hourglass.circle") .foregroundStyle(.yellow) .font(.title) } else if applicant.applicationStatus == ApplicationStatus.waitingForApplicant { Image(systemName: "person.circle") .foregroundStyle(.yellow) .font(.title) } else { Image(systemName: "yieldsign") .foregroundStyle(.yellow) .font(.title) } } } } .onDelete(perform: deleteItems) } } else { ContentUnavailableView { Label("No Applicants", systemImage: "pencil.fill") } } } .navigationTitle("Applicants") .toolbar { ToolbarItem(placement: .navigationBarTrailing) { EditButton() } ToolbarItem { Button(action: addApplicant) { Label("Add Item", systemImage: "plus") } } } .sheet(item: $newApplicant) { applicant in NavigationStack { ApplicantView(applicant: applicant, isNew: true) } } } private func addApplicant() { withAnimation { let newItem = Applicant() modelContext.insert(newItem) newApplicant = newItem } } private func deleteItems(offsets: IndexSet) { withAnimation { for index in offsets { modelContext.delete(applicants[index]) } } } func formattedDate(_ date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .none return dateFormatter.string(from: date) } } import SwiftData @Model final class Applicant { var name = "" var email = "" var phoneNumber = "" var applicationDate = Date.now var expirationDate: Date { return Calendar.current.date(byAdding: .day, value: 90, to: applicationDate)! }
1
0
192
2w
Is SwiftData's #Unique currently broken or am I missing something?
Hi, I am inserting two models where the "unique" attribute is the same. I was under the impression, that this should result in an upsert and not two inserts of the model, but that is not the case. See the test coding below for what I am doing (it is self contained, so if you want to try it out, just copy it into a test target). The last #expect statement fails because of the two inserts. Not sure if this is a bug (Xcode 16 beta 2 on Sonoma running an iOS 18 simulator) or if I am missing something here... // MARK: - UniqueItem - @Model final class UniqueItem { #Unique<UniqueItem>([\.no]) var timestamp = Date() var title: String var changed = false var no: Int init(title: String, no: Int) { self.title = title self.no = no } } // MARK: - InsertTests - @Suite("Insert Tests", .serialized) struct InsertTests { var sharedModelContainer: ModelContainer = { let schema = Schema([ UniqueItem.self, ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() @Test("Test unique.") @MainActor func upsertAndModify() async throws { let ctx = sharedModelContainer.mainContext try ctx.delete(model: UniqueItem.self) let item = UniqueItem(title: "Item \(1)", no: 0) ctx.insert(item) let allFD = FetchDescriptor<UniqueItem>() let count = try ctx.fetchCount(allFD) #expect(count == 1) let updatedItem = UniqueItem(title: "Item \(1)", no: 0) updatedItem.changed = true ctx.insert(updatedItem) // we should still have only 1 item because of the unique constraint let allCount = try ctx.fetchCount(allFD) #expect(allCount == 1) } }
0
1
193
2w
SwiftData PersistentIdentifier saved to UserDefaults?
Hi, I'm updating my app from CoreData to SwiftData and came across an issue. My app has multiple users so in CoreData and I assigned each a myID value set to an UUID so I could use UserDefaults to set the preferred user on app load. When switching over I noticed the PersistentIdentifier value and got excited as I could fetch the matching entity with modelContext.model(for: yourID). I decided to use that instead so I updated my UserDefaults code from UUID to this: @Published var selectedUserID: PersistentIdentifier? { didSet { UserDefaults.standard.set(selectedUserID, forKey: "selectedUserID") } } init() { self.selectedUserID = UserDefaults.standard.object(forKey: "selectedUserID") as? PersistentIdentifier ?? nil } This code compiles and, of course the id is currently set to nil. My issue now is when I try to assign a user to it ar my app crashes and I get the following error: Attempt to set a non-property-list object SwiftData.PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://6FE80FC9-0B4C-491E-8093-DED37A619F1B/EnteredUser/p834), implementation: SwiftData.PersistentIdentifierImplementation) as an NSUserDefaults/CFPreferences value for key selectedUserID Should I go back to an additional UUID field in my user model and find it that way or is there a way to use the PersistentIdentifier value with my UserDefaults? Thanks for any tips.
3
0
543
Nov ’23
SwfitData Crashes after MigrationPlan Completed
There are multiple versions of VersionedSchema in my App. I used MigrationPlan to migrate data. It works well in Xcode, but in TestFlight and App Store, it always crashes when opening the App for the first time. MeMigrationPlan Code: import Foundation import SwiftData enum MeMigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [MeSchemaV1.self, MeSchemaV2.self, MeSchemaV3.self, MeSchemaV4.self] } static var stages: [MigrationStage] { [migrateV1toV2, migrateV2toV3, migrateV3toV4] } //migrateV1toV2, because the type of a data field in MeSchemaV1.TodayRingData.self is modified, the historical data is deleted during migration, and the migration work is successfully completed. static let migrateV1toV2 = MigrationStage.custom( fromVersion: MeSchemaV1.self, toVersion: MeSchemaV2.self, willMigrate: { context in try context.delete(model: MeSchemaV1.TodayRingData.self) }, didMigrate: nil ) //migrateV2toV3, because a new Model was added, it would crash when starting up when TF and the official version were updated, so I tried to delete the historical data during migration, but the problem still exists. static let migrateV2toV3 = MigrationStage.custom( fromVersion: MeSchemaV2.self, toVersion: MeSchemaV3.self, willMigrate: { context in try context.delete(model: MeSchemaV2.TodayRingData.self) try context.delete(model: MeSchemaV2.HealthDataStatistics.self) try context.delete(model: MeSchemaV2.SportsDataStatistics.self) try context.delete(model: MeSchemaV2.UserSettingTypeFor.self) try context.delete(model: MeSchemaV2.TodayRingData.self) try context.delete(model: MeSchemaV2.TodayHealthData.self) try context.delete(model: MeSchemaV2.SleepDataSource.self) try context.delete(model: MeSchemaV2.WorkoutTargetData.self) try context.delete(model: MeSchemaV2.WorkoutStatisticsForTarget.self) try context.delete(model: MeSchemaV2.HealthDataList.self) }, didMigrate: nil ) //migrateV3toV4, adds some fields in MeSchemaV3.WorkoutList.self, and adds several new Models. When TF and the official version are updated, it will crash at startup. Continue to try to delete historical data during migration, but the problem still exists. static let migrateV3toV4 = MigrationStage.custom( fromVersion: MeSchemaV3.self, toVersion: MeSchemaV4.self, willMigrate: { context in do { try context.delete(model: MeSchemaV3.WorkoutList.self) try context.delete(model: MeSchemaV3.HealthDataStatistics.self) try context.delete(model: MeSchemaV3.SportsDataStatistics.self) try context.delete(model: MeSchemaV3.UserSettingTypeFor.self) try context.delete(model: MeSchemaV3.TodayRingData.self) try context.delete(model: MeSchemaV3.TodayHealthData.self) try context.delete(model: MeSchemaV3.SleepDataSource.self) try context.delete(model: MeSchemaV3.WorkoutTargetData.self) try context.delete(model: MeSchemaV3.WorkoutStatisticsForTarget.self) try context.delete(model: MeSchemaV3.HealthDataList.self) try context.delete(model: MeSchemaV3.SleepStagesData.self) try context.save() } catch { print("Migration from V3 to V4 failed with error: \(error)") throw error } }, didMigrate: nil ) }
1
0
123
2w
Using NSFetchedResultsController with viewContext seems to have bad performance
Hello! Our team have been using a NSFetchedResultsController with viewContext for list UI. But we found some UI Hang logs, and I'm guessing that it happens because of Faulting in viewContext. The main thread call stacks in the logs look like below. 0 libsystem_kernel.dylib 0x00000001f378dbcc kevent_id + 8 1 libdispatch.dylib 0x00000001b4047b0f _dispatch_kq_poll + 227 2 libdispatch.dylib 0x00000001b40484df _dispatch_event_loop_wait_for_ownership + 435 3 libdispatch.dylib 0x00000001b4034983 __DISPATCH_WAIT_FOR_QUEUE__ + 339 4 libdispatch.dylib 0x00000001b403454b _dispatch_sync_f_slow + 147 5 CoreData 0x00000001b42859b3 _perform + 203 6 CoreData 0x00000001b4372767 -[NSManagedObjectContext+ 1275751 (_NestedContextSupport) newValuesForObjectWithID:withContext:error:] + 163 7 CoreData 0x00000001b424cf87 _PFFaultHandlerLookupRow + 275 8 CoreData 0x00000001b424cbbf _PF_FulfillDeferredFault + 191 9 CoreData 0x00000001b424cab7 _pvfk_header + 167 10 CoreData 0x00000001b424c9d7 _sharedIMPL_pvfk_core + 31 11 Works 0x000000010445517b closure #1 in static MailUIMailFactory.make(mail:needFolderName:) + 26530171 (MailUIMailFactory.swift:109) ... 0 libsystem_kernel.dylib 0x00000001dbd4254c kevent_id + 8 1 libdispatch.dylib 0x000000019b7057d3 _dispatch_kq_poll + 227 2 libdispatch.dylib 0x000000019b7061bb _dispatch_event_loop_wait_for_ownership + 435 3 libdispatch.dylib 0x000000019b6f2593 __DISPATCH_WAIT_FOR_QUEUE__ + 339 4 libdispatch.dylib 0x000000019b6f215b _dispatch_sync_f_slow + 147 5 CoreData 0x000000019b94f24b _perform + 203 6 CoreData 0x000000019ba3c41b -[NSManagedObjectContext+ 1274907 (_NestedContextSupport) newValueForRelationship:forObjectWithID:withContext:error:] + 167 7 CoreData 0x000000019b914387 -[NSFaultHandler retainedFulfillAggregateFaultForObject:andRelationship:withContext:] + 391 8 CoreData 0x000000019b9118bf -[_NSFaultingMutableSet willReadWithContents:] + 391 9 CoreData 0x000000019b91e663 -[_NSFaultingMutableSet count] + 23 10 Foundation 0x0000000192dbeb3f -[NSSet+ 7609151 (NSKeyValueSorting) sortedArrayUsingDescriptors:] + 55 11 Works 0x000000010249ec1f specialized static MailUIMailFactory.make(mail:needFolderName:) + 27470879 (MailUIMailFactory.swift:102) ... We just use NSFetchedResultsController's fetchedObjects in table view's cellForRowAt method, and make a new model by MailUIMailFactory.make. So we're thinking that we need to initialize NSFetchedResultsController with bg Context. What you guys think? Do I avoid using viewContext in heavy UI?
0
0
154
2w
Sqlite database locked
Hi guys, 🙏I have a problem with repeated saving to the database. If I do the first update it is OK, but after the second attempt the update fails and the console says "Failed to commit transaction: database is locked". Here is my function: func updateMapCoordinates(radius: Int32) { // Otevření databáze, pokud není otevřená guard db != nil else { print("Database connection is nil") return } var statement: OpaquePointer? = nil let updateQuery = "UPDATE \(mapTable) SET radius = ? WHERE id = 1;" // Začátek transakce if sqlite3_exec(db, "BEGIN TRANSACTION", nil, nil, nil) != SQLITE_OK { let errorMessage = String(cString: sqlite3_errmsg(db)) print("Failed to begin transaction: \(errorMessage)") return } if sqlite3_prepare_v2(db, updateQuery, -1, &statement, nil) == SQLITE_OK { sqlite3_bind_int(statement, 1, radius) print("uložím \(radius)") if sqlite3_step(statement) == SQLITE_DONE { print("Coordinates saved successfully") } else { let errorMessage = String(cString: sqlite3_errmsg(db)) print("Failed to save coordinates: \(errorMessage)") } } else { let errorMessage = String(cString: sqlite3_errmsg(db)) print("SAVE statement could not be prepared: \(errorMessage)") } // Finalizace statementu sqlite3_finalize(statement) // Ukončení transakce if sqlite3_exec(db, "COMMIT", nil, nil, nil) != SQLITE_OK { let errorMessage = String(cString: sqlite3_errmsg(db)) print("Failed to commit transaction: \(errorMessage)") sqlite3_exec(db, "ROLLBACK", nil, nil, nil) } }
1
0
206
3w
CoreData result class has 'Sendable' warnings
In an iOS viewController, I use the NSDiffableDataSource to populate a tableView from the results of a CoreData fetchController. The result class is defined by CoreData - in this case a class named CDFilterStack. In xCode 16.0 Beta with strict concurrency checking = 'Complete' the CDFilterStack class has this warning everywhere it is referenced. "Type 'CDFilterStack' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode." The class definition of CDFilterStack is not editable because it is generated by CoreData. I think I need to mark this class (and other similar classes) as @preconcurrency... but how & where? Here's one method sample that generates three of these warnings func initialSnapShot() -> NSDiffableDataSourceSnapshot<Int, CDFilterStack> { var snapshot = NSDiffableDataSourceSnapshot<Int, CDFilterStack>() if let sections = dataProvider.fetchedResultsController.sections { for index in 0..<sections.count { let thisSection = sections[index] guard let sectionStacks = thisSection.objects as? [CDFilterStack] else { continue} snapshot.appendSections([index]) snapshot.appendItems(sectionStacks) } // for loop that will continue on error in objects } return snapshot } Careful reading of the various migration guides hasn't produced an example of how to handle this.. (btw the migration guides are nicely done:)
1
0
223
3w
iPadOS 18 Beta and SwiftData issues
I had a series of @Model classes with some mandatory attributes and some optional. Pre-move to 18, everything was working fine. After the migration, it reports that every single non-Optional attribute is nil upon trying to save. The error is CoreData related but not sure if its in the Core layer or Swift layer. Sample error (with app data removed) is : SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=1560 "Multiple validation errors occurred." Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x30388b2a0> NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=systemName, NSValidationErrorValue=null}" I have modified the code to provide default values for all constructors in an attempt to see a difference, but get the same errors
0
1
220
3w
Library/Caches for app groups: automatically deleted when needed ?
In an app we can use FileManager.SearchPathDirectory.cachesDirectory (objc:NSCachesDirectory) to store files that could be recreated if necessary (and will be automatically deleted by iOS in cases of low disk memory). For app groups, there is a shared location that is automatically created as soon as we use containerURL(forSecurityApplicationGroupIdentifier:) (objc:containerURLForSecurityApplicationGroupIdentifier) : Library/Caches Is this cache directory (created by iOS) also gets automatically deleted by iOS in cases of low disk memory ? I also have more related questions : does this cache directory size count in the used disk space by the app displayed in the settings app ? is this cache directory (and same question for the top containerURL directory) saved in the cloud backups ? Does anyone have any information about this?
4
0
226
3w
`Task` at `createSampleData` function in What's new in SwiftData session
I was looking to the example code that point from What's new in SwiftData session and noticed something that I cannot understand about Swift concurrency. from this snippet: static func createSampleData(into modelContext: ModelContext) { Task { @MainActor in let sampleDataTrips: [Trip] = Trip.previewTrips let sampleDataLA: [LivingAccommodation] = LivingAccommodation.preview let sampleDataBLT: [BucketListItem] = BucketListItem.previewBLTs let sampleData: [any PersistentModel] = sampleDataTrips + sampleDataLA + sampleDataBLT sampleData.forEach { modelContext.insert($0) } if let firstTrip = sampleDataTrips.first, let firstLivingAccommodation = sampleDataLA.first, let firstBucketListItem = sampleDataBLT.first { firstTrip.livingAccommodation = firstLivingAccommodation firstTrip.bucketList.append(firstBucketListItem) } if let lastTrip = sampleDataTrips.last, let lastBucketListItem = sampleDataBLT.last { lastTrip.bucketList.append(lastBucketListItem) } try? modelContext.save() } } From the code snippet, I cannot see any task that needs to be marked with await, and it is also marked as @MainActor. My question is: why do we need to put Task here? It seems like all the code will run on the main thread anyway. I am just afraid that I might be missing some concept of Swift concurrency or SwiftData here. Thank you
2
0
289
3w
Social network app & posting content via a server
Hello, I have had an app that I created myself with Xcode for a long time and I also had it briefly for about two months as a beta in the App Store. At some point I had to take them out because I couldn't solve the problem with a server. I wanted to have a server via iCloud, Kit and Fire Base to upload and display content such as text images, videos. It should be an app that is very similar or the same as TikTok and Instagram just more data protection more 3-D visual design just a modern design and much better built than TikTok Instagram. Unfortunately, I didn't get it or almost Fire Base did it but the problem is that he always says yes this picture or this video or other error message were displayed, but among other things this error message was displayed. Hold this content can't be found in the server or something like that maybe someone here knows what she can do or knows about Fire Base maybe I did something wrong but actually I really taped everything at Fire Base and checked and switched everything on but nothing worked. I hope you can help me.
0
0
186
3w
I'm using CloudKit+CoreData to sync ... looking for faster alternative channel when multiple computers are editing at same time
I am using CloudKit+CoreData to store and sync and share my apps data. In my somewhat limited testing this is working quite well, but sync performance is unpredictable. Often it is very fast, sometimes it just stops until I put Mac app in background or restart. I guess from this thread this behavior is by design: https://developer.apple.com/forums/thread/756315 I'm accepting that! :) My plan is that I will use CloudKit+CoreData for source of truth syncing, but now I'm looking for an alternative channel that I can use to sync when multiple devices are working on this data at the same time. I think the basic design could be: When a device starts editing a CKRecord Post device IP and record ID to well known location/discovery service Watch that location to see other devices that are editing that record Make direct connection to those devices and sync through that connection (still also saving/merging with iCloud). I think I know how to solve the data merge problems that will show up in this scenario, but I don't know what technologies I should use to create the sync channel. I'm looking for ideas. I don't want to run my own server. SharePlay session seems almost perfect, but I'm not sure if it's really intended for this purpose. In particular I would want the session to start automatically (using participants from CKShare) without users having to manually join. Also I would like it to work with a single account (when I am viewing same data on my Mac and iOS device). My other thought is that I would store active users+ip's in the synced CloudKit+CoreData store and then use Network.framework to connect and sync those active users. I think this could work, but is quite low level and might be a lot of work. Are there other options that I'm missing or things I should think about? Thanks, Jesse
0
0
141
3w