In NSFileManager there is this method to move files to and from iCloud:- (BOOL)setUbiquitous:(BOOL)flag itemAtURL:(NSURL *)url destinationURL:(NSURL *)destinationURL error:(NSError **)errorOutAll the samples and information I'm able to find seem to be related to using NSDocument, which my app isn't using. I have a little view in my app that allows users to move an image out from the iCloud container and into a local directory. It seems that simply using NSFileManager moveItemAtURL:toURL:error: works fine both to move a file in and out of the iCloud container on OS X without wrapping everything in a file coordinator block. Is it still necessary to use a file coordinator to move files out of iCloud on the Mac. When I put a file in the iCloud container, the system automatically starts uploading it..even though I'm not using a file coordinator...and my related file presenter still is detecting a change.Both methods seem to be working the same, I'm just wondering if I should be using a coordinator because it's a good amount of code I can get rid of if it's not necessary.Thanks.
CloudKit
RSS for tagStore structured app and user data in iCloud containers that can be shared by all users of your app using CloudKit.
Posts under CloudKit tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hello.I am starting working with theCloudKit Web ServicesI am reading the documentation here:https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/SettingUpWebServices/SettingUpWebServices.html#//apple_ref/doc/uid/TP40015240-CH24-SW1I am trying to receive Getting the Web Authentication TokenAfter successfully login I am getting this jsonObject appInfo:Object
AdditionalSalt:"cec2731125ded8d34cbd3702e0c360b8b7b534fa04dbb2f0ea150b524b7739e5"AppDiscoverable:"false"AppId:"0"AppName:"iCloud.jovan.PhotoWebApp"ContainerEnvironment:"development"ContainerId:"iCloud.jovan.PhotoWebApp"DeveloperName:"UNKNOWN_DEVELOPER"LogoURL:""__proto__:ObjectckSession:"48__24__AZLhIol7ffB34oNYrGP54rWKY5MiVdO+2+85oIiWPuKoK/KJ7r9cNivNwYd03iX/aDW6KL4wuAOVJZ0dAShqhT9ZhoUuW9ZZNPPQ7tzTcBNJ/itQI/uulkBi/51Rpijv/5ZypUYD9yGP3dyXQgDVlGSK8tUPHigigN7nO91DGkM1kaT11lXFBBCHlvZr0DX4tp1cxZ9/P/Q=__eyJYLUFQUExFLVdFQkFVVEgtUENTLUNsb3Vka2l0IjoiUVhCd2JEb3hPZ0VpWXd2Q0QyYmdCVWZrblo1cmp3dnl3Wjg1cHF1dTdLaFZPMThnMEx1bDhLeWRhMHR5SkhyUkZwT0JycEVicXNXWGhqUk9XbTlyd2pkZzB6K3JvZktOIiwiWC1BUFBMRS1XRUJBVVRILVBDUy1TaGFyaW5nIjoiUVhCd2JEb3hPZ0ZyZzEyZGNZSGk4WWRKYU0yK1pFMFRKaytrdTBBMmNZTG8vaUJPRlV1cEtKT3ExS1YvYjlBaldCeklwQTR5N2FUbXNrMDhCWjRsYVRoeWRTaSt3eE9PIn0="isICDP:falsepcsDeleted:falsepermissions:Array[1]
0:Object
ask:falsename:"discoverability"__proto__:Objectlength:1__proto__:Array[0]status:0But, as per documentation I should receive the ckWebAuthToken instead of ckSessionCould you please help me? Looks like documenttion is incorrect or i do something wrong...How to get the ckWebAuthToken or how to use this ckSession for requesting the web services?
Hello,I am creating a new app that uses CKShare. I am able to create the CKShare and send it by email using UICloudSharingController.When the receiver of the invite tries to accept the share, there is an error message"Couldn't open "Title"You need a newer version of "App" to open this, but the required version couldn't be found in the App StoreMy app has not been published to app store yet. How do I resolve this error? I am using a development build with two apple id's to test ckshare.Thanks!
Hello, I'am an Unity game developer. Iam using custom Binary files to save game progress data (encoded strings, int, bool etc.). Now before I build my project/game to Xcode and upload it to the Appstore, I want the user to be able to save their progress to the iCloud so they can play on multiple devices and restore/override their game data if needed. However I can't find online a step for step guide on how to achieve this. The data that I would need to store for 1 user would probably not be more then 100 int/bool/float etc. I want to know what "Cloud system" I should use in my situation, and how to synchronize my binary files to iCloud. Help would very much be appreciated!
Any insights on how to incorporate CloudKit (or CoreData) in the WidgetKit extension? Where in the WidgetKit api do I make the asynchronous call to load the data to be available for the TimelineProvider?
I use NSPersistentCloudKitContainer. It seems that it the data synced in iCloud after a few seconds. However, I get the following warnings in the console. I do not understand what is it for.
CoreData: warning: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(813): <NSCloudKitMirroringDelegate: 0x280b051e0>: Successfully set up CloudKit integration for store: <NSSQLCore: 0x280024a00> (URL: file:///private/var/mobile/Containers/Shared/AppGroup/89D9D17C-03DF-48E4-83C3-DB23A8FE0D6F/TestData.sqlite)
CoreData: warning: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndScheduleImportIfNecessary:]_block_invoke(2033): <NSCloudKitMirroringDelegate: 0x280b051e0>: Scheduling automated import with activity: <CKSchedulerActivity: 0x281f51590; additionalXPCActivityCriteria={
Priority = Utility;
}, containerID=<CKContainerID: 0x283c612e0; containerIdentifier=iCloud.io.test.testData, containerEnvironment="Sandbox">, identifier=com.apple.coredata.cloudkit.activity.import, priority=2>
Could you please explain what is this warning for and what should I do to fix it?
I used a renaming identifier to rename an Entity Name, but it doesn't seem to work and it causes a crash at start during in-place migration.
How to rename an Entity Name when using NSPersistentCloudKitContainer?
I get this exception at start:
CloudKit integration forbids renaming 'OldEntityName' to 'NewEntityName'. Older devices can't process the new records.
Unresolved error Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration."
App is not in production, need a way to rename 'OldEntityName' to 'NewEntityName'. How to achieve this?
I've been using CloudKit for my app recently and I'm trying to add support for a WatchOS app and I've enabled iCloud in capabilities and ticked the container I want to use but I get this error.
CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromPartialError:forStore:inMonitor:]block_invoke(1943): <NSCloudKitMirroringDelegate: 0x282430000>: Found unknown error as part of a partial failure: <CKError 0x28112d500: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; uuid = ; container ID = "iCloud.Appname">
I tried creating a new container which worked for both the watch app and iOS app however I would like to use my original container since it has my old data
Hi.
Didn't find the answer in the documentation. Are CloudKit procedures executables in background tasks ?
I'm trying to do :
"[privateDatabase fetchRecordWithID:myMasterRecordID completionHandler:^(CKRecord *myMasterRecord, NSError *error) { ... }]"
but it returns a record only when the app is active. In background task, it does nothing and waits until app is active.
Thanks for you answer.
Best
Claude
I have an existing app which uses a JSON-based file format currently saved to Application Support (so not user visible). It only needs a single data store per-user.
I would like to integrate it with iCloud to make this file available on other devices.
Is it considered acceptable to use UIDocument on its own for loading/saving the single file?
By this I mean without using UIDocumentBrowserViewController or another file picker. Just my app loading right into the main UI but using UIDocument to open/read/save/close the data file.
I am hoping this would allow me to let UIDocument do most of the boilerplate work around NSFileCoordinator and NSFilePresenter.
Can anyone confirm if this is a thing that is known to be OK? Or am I going against the frameworks here?
I have an app that is already running with CoreData, and I want to allow the users to upload their data to iCloud so, in the case they need to delete their apps or change devices, they don't lose it.
Every time the app is opened, there is a synchronization that happens between CoreData and a JSON file fixture, in order to fill the app with its base values (creating NSManagedObject instances from the aforementioned fixture).
Before the iCloud sync, the CoreData model had some constraints for different entities, to enforce uniqueness, but these had to be stripped since CloudKit doesn't support them. Most of these constraints were basically ids that came from the JSON and represent an item in our Firebase database.
Given that, I want to make the underlying CKRecord.id the same as these ids, so I can avoid the situation where, if a person open the app in a second device, the fixture data is repeated, since the fixture runs before the sync with the iCloud happens.
Is that possible? Any help would be appreciated.
In my app I have a defaultJournal: Journal, that automatically gets added on the user's device on launch. There should only be one "default" journal, and I know that deduplication as shown in the Apple Demo, is the correct approach to ensure this on multiple devices. Journal looks something like:
class Journal: NSManagedObject {
@NSManaged var isDefaultJournal: Bool
@NSManaged var entries: Set<JournalEntry>?
}
Since Journal has a relationship to entries, how can I deduplicate it ensuring that I don't orphan or delete the entries?
I am worried that the entries aren't guaranteed to be synced, when we discover a duplicate journal in processPersistentHistory.
This would lead to either orphaned or deleted entries depending on the deletion rule.
How can one handle deduplicating entities with relationships?
For example here is my remove function:
func remove(duplicateDefaultCalendarNotes: [Journal], winner: Journal, on context: NSManagedObjectContext) {
duplicateDefaultCalendarNotes.forEach { journal in
defer { context.delete(journal) }
// FIXME: What if all of the journal entries have not been synced yet from the cloud?
// Should we fetch directly from CloudKit instead? (could still lead to orphaned/deleted journal that have not yet been uploaded)
guard let entries = journal.entries else { return }
entries.forEach {
$0.journal = winner
}
}
}
A missing tag on a post isn't that bad, but deleting a user's journal is unacceptable. What is the best strategy to handle this?
I'm using NSPersistentCloudKitContainer with Core Data and I receive errors because my iCloud space is full. The errors printed are the following: <CKError 0x280df8e40: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = 61846C533467A5DF; uuid = 6A144513-033F-42C2-9E27-693548EF2150; Retry after 342.0 seconds>.
I want to inform the user about this issue, but I can't find a way to access the details of the error. I'm listening to NSPersistentCloudKitContainer.eventChangedNotification, I receive a error of type .partialFailure. But when I want to access the underlying errors, the partialErrorsByItemID property on the error is nil.
How can I access this Quota Exceeded error?
import Foundation
import CloudKit
import Combine
import CoreData
class SyncMonitor {
fileprivate var subscriptions = Set<AnyCancellable>()
init() {
NotificationCenter.default.publisher(for: NSPersistentCloudKitContainer.eventChangedNotification)
.sink { notification in
if let cloudEvent = notification.userInfo?[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event {
guard let ckerror = cloudEvent.error as? CKError else {
return
}
print("Error: \(ckerror.localizedDescription)")
if ckerror.code == .partialFailure {
guard let errors = ckerror.partialErrorsByItemID else {
return
}
for (_, error) in errors {
if let currentError = error as? CKError {
print(currentError.localizedDescription)
}
}
}
}
} // end of sink
.store(in: &subscriptions)
}
}
Are there good examples of integrating SwiftUI, Coredata and Cloudkit working nicely together?
Hi everyone, we recently integrated UICloudSharingController to share cloudkit records on one of our apps, but we noticed while testing that the icloud share link opens the wrong app on App Store if we invite a participant who has not the app installed on his device.
We thought it was because for another our app (app store opens the download page for this app) we basically duplicated the same coredata/cloudkit implementation, forgetting maybe some cloudkit references of the first app and indeed we noticed a wrong icloud container assignment for the second app, which essentially had two containers, the correct one (its own) and the one of the first app (the wrong one).
So, we fixed the problem, every app has his own container now and only his own, and we updated the provisional profiles as well, in order to have the correct icloud containers entitlements. Unfortunately the problem persists and after check everything else (containers, app groups, PersistentStoreDescriptions etc.) we don't have any more ideas.
What else should we check? Thanks in advance for your suggestions.
Some more detail of the issue:
If we have the app installed on the device the icloud share link opens the right app.
The same icloud share link works properly on Mac Catalyst (the App Store opens the correct app page if we don't have the app installed). The problem is only on iOS.
I'm using Xcode 14 beta 4, on macOS Monterey 12.5, developing a Mac app that's using CoreData CloudKit sync — with my context being configured with two configurations (one for a local cache and one data synced via CloudKit).
An issue recently appeared where the app crashes soon after start-up with this message:
[threadmgrsupport] _TSGetMainThread_block_invoke:Main thread potentially initialized incorrectly, cf <rdar://problem/67741850>
And this stack trace:
Thread 1 Queue : com.apple.main-thread (serial)
#0 0x000000018b86b5e8 in ___NSAssertMainEventQueueIsCurrentEventQueue_block_invoke ()
#1 0x0000000105b563a8 in _dispatch_client_callout ()
#2 0x0000000105b58300 in _dispatch_once_callout ()
#3 0x000000018b86a2dc in _DPSNextEvent ()
#4 0x000000018b868e14 in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] ()
#5 0x000000018b85afe0 in -[NSApplication run] ()
#6 0x000000018b82c6fc in NSApplicationMain ()
#7 0x00000001ae281e98 in specialized runApp(_:) ()
#8 0x00000001aee10588 in runApp<τ_0_0>(_:) ()
#9 0x00000001ae88626c in static App.main() ()
Things work again, if I disable the CloudKit sync by not setting cloudKitContainerOptions on my "Cloud" configuration. Similarly, it works on first install, but reappears on subsequent runs. The code is in a package that's shared with an iOS version of the app, which has no such issues.
I also tried going back to previous commits that worked before, and it works again until at some point it stops working again for the same commits. So it doesn't seem to be caused directly by my code, but rather by something that the CloudKit sync is doing.
Any help would be much appreciated.
Before the code...
CloudKit, background mode (remote notifications) and push notifications are added to Capabilities.
Background sync is working fine and view loads current store on manual fetch.
Code that initialises the persistent container in app delegate...
- (NSPersistentCloudKitContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentCloudKitContainer alloc] initWithName:@"Expenses"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
__block NSPersistentStoreDescription *sDescription = storeDescription;
dispatch_async(dispatch_get_main_queue(), ^(){
[sDescription setOption:[NSNumber numberWithBool:YES] forKey:@"PersistentHistoryTracking"];
[sDescription setOption:[NSNumber numberWithBool:YES] forKey:@"NSPersistentStoreRemoteChangeNotificationOptionKey"];
});
#ifdef DEBUG
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
#endif
abort();
}
else
#ifdef DEBUG
NSLog(@"Store successfully initialized");
#endif
}];
}
}
return _persistentContainer;
}
In Home view controller which is the initial view controller i am adding an observer for the remote notification...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadViewONCKChangeNotification) name:NSPersistentStoreRemoteChangeNotification object:[appDelegate.persistentContainer persistentStoreCoordinator]];
I am not receiving any store change notifications. Have added breakpoints to see if selector is fired. no go.
CloudKit Console also doesn't show any pushes for the concerned time period.
I've found old forum posts that reference CloudKit pricing based on usage (after exceeding the 'Free' tier). However, it doesn't seem that Apple has any information on any of their website that indicate what that pricing is, or otherwise the limits of a free tier.
The closest I've found to this is on https://developer.apple.com/icloud/cloudkit/ where it says, "Store private data securely in your users’ iCloud accounts for limitless scale as your user base grows, and get up to 1PB of storage for your app’s public data."
So does this mean that the only CloudKit limits now are:
Private data: dependent on individual user's remaining iCloud storage space
Public data: 1 PB
Request count/day: unlimited
Download usage/day: unlimited
I'm being a little sarcastic, but at the same time, if there are still limits and a pricing structure, I'm really scratching my head as to why that doesn't seem to be published anywhere.
Ultimately, I'm trying to find the best, reliable public asset storage with cross-device usage (iOS, tvOS) solution and am weighing CloudKit versus other cloud storage solutions and their costs.
Side note: I'm kinda confused why CloudKit provides public asset storage in the first place, since I thought On-Demand Resources was intended to fill that gap (and ODR does have storage limits too).
I'm building a macOS + iOS SwiftUI app using Xcode 14.1b3 on a Mac running macOS 13.b11. The app uses Core Data + CloudKit.
With development builds, CloudKit integration works on the Mac app and the iOS app. Existing records are fetched from iCloud, and new records are uploaded to iCloud. Everybody's happy.
With TestFlight builds, the iOS app has no problems. But CloudKit integration isn't working in the Mac app at all. No existing records are fetched, no new records are uploaded.
In the Console, I see this message:
error: CoreData+CloudKit: Failed to set up CloudKit integration for store: <NSSQLCore: 0x1324079e0> (URL: <local file url>)
Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction.}
I thought it might be that I was missing the com.apple.security.network.client entitlement, but adding that didn't help.
Any suggestions what I might be missing? (It's my first sandboxed Mac app, so it might be really obvious to anyone but me.)
Hello,
I've created multiple Entity in CoreData, that has a relationship to one another. However, I'm unable to create @discardableResult to use in SwiftUI preview.
/// Entity data for use with canvas previews.
static var preview: Entity1 {
let entities1 = Entity1.makePreviews(count: 1)
return entities1[0]
}
@discardableResult
static func makePreviews(count: Int) -> [Entity1] {
var contents = [Entity1]()
let viewContext = PersistenceController.preview.container.viewContext
let persistenceController = PersistenceController.shared
for index in 0..<count {
let entities1 = Entity1(context: viewContext)
entities1.id = UUID()
entities1.title = "Amazing day!"
let photo = Photo(context: viewContext)
let imageData = UIImage(named: "Golden Temple")?.jpegData(compressionQuality: 1) ?? Data()
photo.linkedToJournal = journal
let thumbnail = Thumbnail(context: viewContext)
let thumbnailData = persistenceController.thumbnail(with: imageData)?.jpegData(compressionQuality: 1)
thumbnail.data = thumbnailData
thumbnail.photo = photo
let photoDataObject = PhotoData(context: viewContext)
photoDataObject.data = imageData
photoDataObject.photo = photo
contents.append(entities1)
}
return contents
}
You may also try to use the sample code from https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users to build a SwiftUI Preview.
Appreciate if you could suggest how to build a SwiftUI preview as it saves a lot of development effort and time. Thank you very much!