I have an app that I signed and distribute between some internal testflight users. Potentially I want to invite some 'Public' beta testers which don't need to validate (_World have read rights in the public database)
Question: Do I need to have a working public CloudKit , when users are invited through TestFlight, or are they going to test on the development container?
I understand that when I invite beta-tester without authorization (external testers) they cannot access the developer container, so therefore I need to have the production CloudKit container up and running.
I have tried to populate the public production container, but for whatever reason my upload app still goes to the development container. I have archived the app, and tried, but no luck. I let xcode manage my certificates/profiles. but what do I need to change to be able to use my upload file to upload the production container, instead of the development.
I tried:
init() {
container = CKContainer(identifier: "iCloud.com.xxxx.xxxx")
publicDB = container.publicCloudDatabase
I got no error in the console, but data is always populated to the development database, instead the production.
I tried to create a provisioning profile, but for some reason Xcode doesn't like it. Tried to create one a different provisioning profile manual through the developer portal, for the app. but xcode doesn't want to use that, and mentions that the requirement are already in place.
What can I check/do to solve this.
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I built a SwiftData App that relies on CloudKit to synchronize data across devices.
That means all model relationships must be expressed as Optional.
That’s fine, but there is a limitation in using Optional’s in SwiftData SortDescriptors (Crashes App)
That means I can’t apply a SortDescriptor to ModelA using some property value in ModelB (even if ModelB must exist)
I tried using a computed property in ModelA that referred to the property in ModelB, BUT THIS DOESN”T WORK EITHER!
Am I stuck storing redundant data In ModelA just to sort ModelA as I would like???
I have an app which uses ubiquitous containers and files in them to share data between devices. It's a bit unusual in that it indexes files in directories the user grants access to, which may or may not exist on a second device - those files are identified by SHA-1 hash. So a second device scanning before iCloud data has fully sync'd can create duplicate references which lead to an unpleasant user experience.
To solve this, I store a small binary index in the root of the ubiquitous file container of the shared data, containing all of the known hashes, and as the user proceeds through the onboarding process, a background thread is attempting to "prime" the ubiquitous container by calling FileManager.default.startDownloadingUbiquitousItemAt() for each expected folder and file in a sane order.
This likely creates a situation not anticipated by the iOS/iCloud integration's design, as it means my app has a sort of precognition of files it should not yet know about.
In the common case, it works, but there is a corner case where iCloud sync has just begun, and very, very little metadata is available (the common case, however, in an emulator), in which two issues come up:
I/O may hang indefinitely, trying to read a file as it is arriving. This one I can work around by running the I/O in a thread created with the POSIX pthread_create and using pthread_cancel to kill it after a timeout.
Attempts to call FileManager.default.startDownloadingUbiquitousItemAt() fails with an error Error Domain=NSCocoaErrorDomain Code=257 "The file couldn’t be opened because you don’t have permission to view it.". The permissions aspect of it is nonsense, but I can believe there's no applicable "sort of exists, sort of doesn't" error code to use and someone punted. The problem is that this same error will be thrown on any attempt to access that file for the life of the application - a restart is required to make it usable.
Clearly, the error or the hallucinated permission failure is cached somewhere in the bowels of iOS's FileManager. I was hoping startAccessingSecurityScopedResource() would allow me to bypass such a cache, as it does with URL.resourceValues() returning stale file sizes and last modified times. But it does not.
Is there some way to clear this state without popping up a UI with an Exit button (not exactly the desired iOS user experience)?
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
Foundation
Files and Storage
iOS
iCloud Drive
I am trying to extend my PersistedModels like so:
@Versioned(3)
@Model
class MyType {
var name: String
init() { name = "hello" }
}
but it seems that SwiftData's@Model macro is unable to read the properties added by my @Versioned macro. I have tried changing the order and it ignores them regardless. version is not added to schemaMetadata and version needs to be persisted. I was planning on using this approach to add multiple capabilities to my model types. Is this possible to do with macros?
VersionedMacro
/// A macro that automatically implements VersionedModel protocol
public struct VersionedMacro: MemberMacro, ExtensionMacro {
// Member macro to add the stored property directly to the type
public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self),
let firstArgument = argumentList.first?.expression else {
throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)")
}
let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces)
// Add the stored property with the version value
return [
"public private(set) var version: Int = \(raw: versionValue)"
]
}
// Extension macro to add static property
public static func expansion(
of node: SwiftSyntax.AttributeSyntax,
attachedTo declaration: some SwiftSyntax.DeclGroupSyntax,
providingExtensionsOf type: some SwiftSyntax.TypeSyntaxProtocol,
conformingTo protocols: [SwiftSyntax.TypeSyntax],
in context: some SwiftSyntaxMacros.MacroExpansionContext
) throws -> [SwiftSyntax.ExtensionDeclSyntax] {
guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self),
let firstArgument = argumentList.first?.expression else {
throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)")
}
let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces)
// We need to explicitly add the conformance in the extension
let ext = try ExtensionDeclSyntax("extension \(type): VersionedModel {}")
.with(\.memberBlock.members, MemberBlockItemListSyntax {
MemberBlockItemSyntax(decl: DeclSyntax(
"public static var version: Int { \(raw: versionValue) }"
))
})
return [ext]
}
}
VersionedModel
public protocol VersionedModel: PersistentModel {
/// The version of this particular instance
var version: Int { get }
/// The type's current version
static var version: Int { get }
}
Macro Expansion:
Hi,
I'm having trouble implementing iCloud Drive in my app. I've already taken the obvious steps, including enabling iCloud Documents in Xcode and selecting a container. This container is correctly specified in my code, and in theory, everything should work.
The data generated by my app should be saved to iCloud Drive in addition to local storage. The data does get stored in the Files app, but the automatic syncing to iCloud Drive doesn’t work as expected.
I’ve also considered updating my .entitlements file.
Since I’m at a loss, I’m reaching out for help maybe I’ve overlooked something important that's causing it not to work. If anyone has an idea, please let me know.
Thanks in advance!
If use a SortDescriptor for a model and sort by some attribute from a relationship, in DEBUG mode it all works fine and sorts. However, in release mode, it is an instant crash.
SortDescriptor(.name, order: .reverse) ---- works
SortDescriptor(.assignedUser?.name, order: .reverse) ---- works in debug but crash in release.
What is the issue here, is it that SwiftData just incompetent to do this?
The app works on a local db but when I try to make it work with iCloud I get errors that I don't understand.
CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1247): <NSCloudKitMirroringDelegate: 0x10664c200>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x106688140> (URL: file:///var/mobile/Containers/Data/Application/20EF350F-F0FA-4132-97DA-61B60AADB101/Library/Application%20Support/default.store)
<CKError 0x109430e40: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = 82ED152A-D015-414D-BB79-AF36E5AF4A8B; container ID = "iCloud.se.Grindegard.MinaRecept"; partial errors: {
com.apple.coredata.cloudkit.zone:defaultOwner = <CKError 0x109431230: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = E56A3CDA393641F8; uuid = 82ED152A-D015-414D-BB79-AF36E5AF4A8B>
}>
what can be wrong?
Topic:
App & System Services
SubTopic:
iCloud & Data
Hi,
I'm implementing iCloud backup functionality in my web application using CloudKit JS, but I'm running into some issues. I'd appreciate any help you can provide.
Issue:
The iCloud backup feature isn't working properly in our web app. I believe I've correctly set up the Apple Developer Program registration and API token generation. While a demo implementation works perfectly with iCloud backup, our app implementation is failing.
Specifically:
"Sign in with Apple" succeeds
However, ck.getDefaultContainer().setupAuth() returns null
In the working demo, setupAuth() returns a proper value
Even after logging in through the redirect URL provided in the "421 Misdirected Request" error response and executing setupAuth(), it still returns null
I've essentially copied the working demo code directly, so I suspect the issue might be related to token generation, permissions, or account configuration.
Questions:
Could you provide detailed step-by-step instructions for implementing iCloud backup in a web application? I've noticed there are configuration items in the Developer Console and Certificates console, so I may have missed something in one of these areas.
Based on the symptoms described, what are the possible causes for setupAuth() returning null in CloudKit JS? Could configuration issues be indirectly causing this, or is it more likely a timing issue or SDK coding problem?
Specifically regarding the 421 error and redirect flow - is there something in the configuration that could cause setupAuth() to return null even after successful authentication through the redirect?
Thanks in advance for your help!
Topic:
App & System Services
SubTopic:
iCloud & Data
Hi everyone,
I’m currently developing a SwiftUI app that uses SwiftData with CloudKit sharing enabled. The app works fine on my own Apple ID, and local syncing with iCloud is functioning correctly — but sharing with other Apple IDs consistently fails.
Setup:
SwiftUI + SwiftData using a ModelContainer with .shared configuration
Sharing UI is handled via UICloudSharingController
iCloud container: iCloud.com.de.SkerskiDev.FoodGuard
Proper entitlements enabled (com.apple.developer.icloud-services, CloudKit, com.apple.developer.coredata.cloudkit.containers, etc.)
Automatic provisioning profiles created by Xcode
Error:<CKError 0x1143a2be0: "Bad Container" (5/1014);
"Couldn't get container configuration from the server for container iCloud.com.de.SkerskiDev.FoodGuard">
What I’ve tried:
Verified the iCloud container is correctly created and enabled in the Apple Developer portal
Checked bundle identifier and container settings
Rebuilt and reinstalled the app
Ensured correct iCloud entitlements and signing capabilities
Questions:
Why does CloudKit reject the container for sharing while local syncing works fine?
Are there known issues with SwiftData .shared containers and multi-user sharing?
Are additional steps required (App Store Connect, privacy settings) to allow sharing with other Apple IDs?
Any advice, experience, or example projects would be greatly appreciated. 🙏
Thanks!
Sebastian
I have some models in my app:
[SDPlanBrief.self, SDAirport.self, SDChart.self, SDIndividualRunwayAirport.self, SDLocationBrief.self]
SDLocationBrief has a @Relationship with SDChart
When I went live with my app I didn't have a versioned schema, but quickly had to change that as I needed to add items to my SDPlanBrief Model.
The first versioned schema I made included only the model that I had made a change to.
static var models: [any PersistentModel.Type] {
[SDPlanBrief.self]
}
I had made zero changes to my model container and the whole time, and it was working fine. The migration worked well and this is what I was using:
.modelContainer(for: [SDAirport.self, SDIndividualRunwayAirport.self, SDLocationBrief.self, SDChart.self, SDPlanBrief.self])
I then saw that to do this all properly, I should actually include ALL of my @Models in the versioned schema:
enum AllSwiftDataSchemaV3: VersionedSchema {
static var models: [any PersistentModel.Type] {
[SDPlanBrief.self, SDAirport.self, SDChart.self, SDIndividualRunwayAirport.self, SDLocationBrief.self]
}
static var versionIdentifier: Schema.Version = .init(2, 0, 0)
}
extension AllSwiftDataSchemaV3 {
@Model
class SDPlanBrief {
var destination: String
etc...
init(destination: String, etc...) {
self.destination = destination
etc...
}
}
@Model
class SDAirport {
var catABMinima: String
etc...
init(catABMinima: String etc...) {
self.catABMinima = catABMinima
etc...
}
}
@Model
class SDChart: Identifiable {
var key: String
etc...
var brief: SDLocationBrief? // @Relationship with SDChart
init(key: String etc...) {
self.key = key
etc...
}
}
@Model
class SDIndividualRunwayAirport {
var icaoCode: String
etc...
init(icaoCode: String etc...) {
self.icaoCode = icaoCode
etc...
}
}
@Model
class SDLocationBrief: Identifiable {
var briefString: String
etc...
@Relationship(deleteRule: .cascade, inverse: \SDChart.brief) var chartsArray = [SDChart]()
init(
briefString: String,
etc...
chartsArray: [SDChart] = []
) {
self.briefString = briefString
etc...
self.chartsArray = chartsArray
}
}
}
This is ALL my models in here btw.
I saw also that modelContainer needed updating to work better for versioned schemas. I changed my modelContainer to look like this:
actor ModelContainerActor {
@MainActor
static func container() -> ModelContainer {
let schema = Schema(
versionedSchema: AllSwiftDataSchemaV3.self
)
let configuration = ModelConfiguration()
let container = try! ModelContainer(
for: schema,
migrationPlan: PlanBriefMigrationPlan.self,
configurations: configuration
)
return container
}
}
and I am passing in like so:
.modelContainer(ModelContainerActor.container())
Each time I run the app now, I suddenly get this message a few times in a row:
CoreData: error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable. This may result in an unstable verison checksum. Add model to NSPersistentStoreCoordinator and try again.
I typealias all of these models too for the most recent V3 version eg:
typealias SDPlanBrief = AllSwiftDataSchemaV3.SDPlanBrief
Can someone see if I am doing something wrong here? It seems my TestFlight users are experiencing a crash every now and then when certain views load (I assume when accessing @Query objects). Seems its more so when a view loads quickly, like when removing a subscription view where the data may not have had time to load??? Can someone please have a look and help me out.
In the CloudKit logs I see logs that suggest users getting QUOTA_EXCEEDED error for RecordDelete operations.
{
"time":"21/07/2025, 7:57:46 UTC"
"database":"PRIVATE"
"zone":"***"
"userId":"***"
"operationId":"***"
"operationGroupName":"2.3.3(185)"
"operationType":"RecordDelete"
"platform":"iPhone"
"clientOS":"iOS;18.5"
"overallStatus":"USER_ERROR"
"error":"QUOTA_EXCEEDED"
"requestId":"***"
"executionTimeMs":"177"
"interfaceType":"NATIVE"
"recordInsertBytes":54352
"recordInsertCount":40
"returnedRecordTypes":"_pcs_data"
}
I'm confused as to what this means? Why would a RecordDelete operation have recordInsertBytes? I'd expect a RecordDelete operation to never fail on quotaExceeded and how would I handle that in the app?
Hi,
I'm getting a very odd error log in my SwiftData setup for an iOS app. It is implemented to support schema migration. When starting the app, it simply prints the following log twice (seems to be dependent on how many migration steps, I have two steps in my sample code):
CoreData: error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable. This may result in an unstable verison checksum. Add model to NSPersistentStoreCoordinator and try again.
(Yes there is a mistyped word "verison", this is exactly the log)
The code actually fully works. But I have neither CloudKit configured, nor is this app in Production yet. I'm still just developing.
Here is the setup and code to reproduce the issue.
Development mac version: macOS 15.5
XCode version: 16.4
iOS Simulator version: 18.5
Real iPhone version: 18.5
Project name: SwiftDataDebugApp
SwiftDataDebugApp.swift:
import SwiftUI
import SwiftData
@main
struct SwiftDataDebugApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self,
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false, allowsSave: true)
do {
return try ModelContainer(for: schema, migrationPlan: ModelMigraitonPlan.self, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
Item.swift:
import Foundation
import SwiftData
typealias Item = ModelSchemaV2_0_0.Item
enum ModelSchemaV1_0_0: VersionedSchema {
static var versionIdentifier = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
}
enum ModelSchemaV2_0_0: VersionedSchema {
static var versionIdentifier = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
var tags: [Tag] = []
init(timestamp: Date, tags: [Tag]) {
self.timestamp = timestamp
self.tags = tags
}
}
}
enum ModelMigraitonPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[ModelSchemaV1_0_0.self]
}
static var stages: [MigrationStage] {
[migrationV1_0_0toV2_0_0]
}
static let migrationV1_0_0toV2_0_0 = MigrationStage.custom(
fromVersion: ModelSchemaV1_0_0.self,
toVersion: ModelSchemaV2_0_0.self,
willMigrate: nil,
didMigrate: { context in
let items = try context.fetch(FetchDescriptor<ModelSchemaV2_0_0.Item>())
for item in items {
item.tags = Array(repeating: "abc", count: Int.random(in: 0...3)).map({ Tag(value: $0) })
}
try context.save()
}
)
}
Tag.swift:
import Foundation
struct Tag: Codable, Hashable, Comparable {
var value: String
init(value: String) {
self.value = value
}
static func < (lhs: Tag, rhs: Tag) -> Bool {
return lhs.value < rhs.value
}
static func == (lhs: Tag, rhs: Tag) -> Bool {
return lhs.value == rhs.value
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
ContentView.swift:
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
VStack {
List {
ForEach(items) { item in
VStack(alignment: .leading) {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
HStack {
ForEach(item.tags, id: \.hashValue) { tag in
Text("\(tag.value)")
}
}
}
}
.onDelete(perform: deleteItems)
}
Button("Add") {
addItem()
}
.padding(.top)
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date(), tags: [Tag(value: "Hi")])
modelContext.insert(newItem)
}
do {
try modelContext.save()
} catch {
print("Error saving add: \(error.localizedDescription)")
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
do {
try modelContext.save()
} catch {
print("Error saving delete: \(error.localizedDescription)")
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
I hope someone can help, couldn't find anything related to this log at all.
Hey all,
This is my first app with Swift, and first app using CloudKit / iCloud - although I have launched other iOS app successfully.
When I created the app, I selected "none" for storage
my bundle identifier looks like this: io.mysite.appname
I have the iCloud capability added, with CloudKit checked, and the container also checked that looks like this: iCloud.io.mysite.appname
Push Notificaitons capability is also added, but there is no configuration.
I have tried automatically managed signing, as well as a manually created provisioning profile..
Every time I build the app onto my device - when I check it out in settings, icloud is not listed. When I go through iCloud into icloud drive, the app is also not listed.
I have cleaned the build many times, deleted and reinstalled the app on my phone many times. I am definitely logged into iCloud etc.
Obviously I have spent plenty of times trying to debug with various LLMs, but we all seem to be at a loss for what I'm missing or doing wrong.
Would love any tips or pointers I may be missing, thank you!
Topic:
App & System Services
SubTopic:
iCloud & Data
Hi,
I am testing a situation with shared CKRecords where the data in the CKRecord syncs fine, but the creatorUserRecordID.recordName and lastModifiedUserRecordID.recordName shows "defaultOwner" (which maps to the CKCurrentUserDefaultName constant) even though I made sure I edit the CKRecord value from a different iCloud account. In fact, on the CloudKit dashboard, it shows the correct user recordIDs in the metadata for the 'Created' and 'Modified' fields, but not in the CKRecord.
I am mostly testing this on the iPhone simulator with the debugger attached. Is that a possible reason for this, or is there some other reason the lastModifiedUserRecordID is showing the value for 'CKCurrentUserDefaultName'? It would be pretty difficult to build in functionality to look up changes by a different userID if this is the case.
Hi, I work on a financial app in Brazil and since Beta 1 we're getting several crashes. We already opened a code level support and a few feedback issues, but haven't got any updates on that yet.
We were able to resolve some crashes changing some of our implementation but we aren't able to understand what might be happening with this last one.
This is the log we got on console:
erro 11:55:41.805875-0300 MyApp CoreData: error: Failed to load NSManagedObjectModel with URL 'file:///private/var/containers/Bundle/Application/0B9F47D9-9B83-4CFF-8202-3718097C92AE/MyApp.app/ServerDrivenModel.momd/'
We double checked and the momd is inside the bundle. The same app works on any other iOS version and if we build using Xcode directly (without archiving and installing on an iOS26 device) it works as expected.
Have anyone else faced a similar error? Any tips or advice on how we can try to solve that?
Hi,
I am experiencing main thread freezes from fetching on Main Actor. Attempting to move the function to a background thread, but whenever I reference the TestModel in a nonisolated context or in another model actor, I get this warning:
Main actor-isolated conformance of 'TestModel' to 'PersistentModel' cannot be used in actor-isolated context; this is an error in the Swift 6 language mode
Is there a way to do this correctly?
Recreation, warning on line 13:
class TestModel {
var property: Bool = true
init() {}
}
struct SendableTestModel: Sendable {
let property: Bool
}
@ModelActor
actor BackgroundActor {
func fetch() throws -> [SendableTestModel] {
try modelContext.fetch(FetchDescriptor<TestModel>()).map { SendableTestModel(property: $0.property) }
}
}
Hi,
I'm considering using the new SwiftData class inheritance for a new app I'm building. I have a few questions:
Is it working well enough for production?
I have a number of different object types in my app. Some of them are very similar, and there's always a balance to be struck when it comes to splitting them into different types using class inheritance. Are there some good advice on when to use multiple classes instead of squeezing my object types into a single class?
Is there advice against using class inheritance in multiple levels (3-4)?
Claes
About 4 months ago, I shipped the first version of my app with 4 versioned schemas that, unintentionally, had the same versionIdentifier of 1.2.0 in 2 of them:
V1: 1.0.0
V2: 1.1.0
V3: 1.2.0
V4: 1.2.0
They are ordered correctly in the MigrationPlan, and they are all lightweight.
Migration works, SwiftData doesn't crash on init and I haven't encountered any issues related to this. The app syncs with iCloud.
Questions, preferable for anybody with knowledge of SwiftData internals:
What will break in SwiftData when there are 2 duplicate numbers?
Not that I would expect it to be safe, but does it happen to be safe to ship an update that changes V4's version to 1.3.0, what was originally intended?
Topic:
App & System Services
SubTopic:
iCloud & Data
Hi, I keep trying to use transformable to store an array of strings with SwiftData, and I can see that it is activating the transformer, but it keeps saying that I am still using NSArray instead of NSData.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "category"; desired type = NSData; given type = Swift.__SwiftDeferredNSArray; value = (
yo,
gurt
).'
terminating due to uncaught exception of type NSException
CoreSimulator 1010.10 - Device: iPhone 16 18.0 (6879535B-3174-4025-AD37-ED06E60291AD) - Runtime: iOS 18.0 (22A3351) - DeviceType: iPhone 16
Message from debugger: killed
@Model
class MyModel: Identifiable, Equatable {
@Attribute(.transformable(by: StringArrayTransformer.self)) var category: [String]?
@Attribute(.transformable(by: StringArrayTransformer.self)) var amenities: [String]?
var image: String?
var parentChunck: HenricoPostDataChunk_V1?
init(category: [String]?, amenities: [String]?) {
self.category = category
self.amenities = amenities
}
}
class StringArrayTransformer: ValueTransformer {
override func transformedValue(_ value: Any?) -> Any? {
print(value)
guard let array = value as? [String] else { return nil }
let data = try? JSONSerialization.data(withJSONObject: array, options: [])
print(data)
return data
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let data = value as? Data else { return nil }
let string = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String]
print(string)
return string
}
override class func transformedValueClass() -> AnyClass {
return NSData.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
static func register() {
print("regitsering")
ValueTransformer.setValueTransformer(StringArrayTransformer(), forName: .stringArrayTransformerName)
}
}
extension NSValueTransformerName {
static let stringArrayTransformerName = NSValueTransformerName("StringArrayTransformer")
}
I have an app that uses NSPersistentCloudKitContainer stored in a shared location via App Groups so my widget can fetch data to display. It works. But if you reset your iPhone and restore it from a backup, an error occurs:
The file "Name.sqlite" couldn't be opened. I suspect this happens because the widget is created before the app's data is restored. Restarting the iPhone is the only way to fix it though, opening the app and reloading timelines does not. Anything I can do to fix that to not require turning it off and on again?