CloudKit - How did my Entities end up in a Private Database (and can I change to Public)? - core-data

In xCode I created some Core Data Entities for my app in the Default Configuration and I set up my Data Controller class as follows:
class DataController: ObservableObject {
let container: NSPersistentCloudKitContainer
class DataController: ObservableObject {
let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "KoyaQuest", managedObjectModel: Self.model)
if inMemory {
container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores { _, error in
if let error = error {
fatalError("Fatal error loading data store: \(error.localizedDescription)")
}
...
}
Over in CloudKit Dashboard, I notice that any records being created are stored in the "Private Database." And I'm not sure how that happened as I don't recall (nor can I find any evidence of) my specifying the type of database. I am in Development. Is this a default of that mode?
Also, since I really want these data to be public, is there a way to make the change? I've scoured Apple's documentation and other sources but can't seem to find a simple answer.
Thanks.

Soon after posting this question, I re-discovered this video (which I had actually watched before!). In case anyone has the same confusion as I did, I'm sharing here. Note that one of the two indices that need to be added to the CloudKit schema seems to have been re-named to "modifiedTimestamp" (at least that's the only one I see that looks close enough to "modifiedAt" as shown in the video).

Related

Implementing ForEach.onMove() with Core Data

I am trying to implement ForEach.onMove using Core Data. I have two entities, Parent with a To-Many relationship to Child, with the relationship marked as Ordered. The view is something like this:
struct ParentView : View {
#ObservedObject var parent : Parent
var body : some View {
List {
ForEach($parent.children! as! [Child]) { child in
ChildView(child)
}.onMove {
parent.managedObjectContext!.performAndWait { indices, to in
(parent.children! as! NSMutableOrderedSet).moveObjects(at: indices, to: to)
try! parent.managedObjectContext!.save()
parent.objectWillChange.send()
}
}
}
}
}
Results are:
No errors of any kind.
During debug of the onMove function, I can see that the items are re-ordered as required
The managedObjectContext.updatedObjects is empty at the same debug step, before the call to save()
When reloading the app, the re-ordering is obviously not saved (apparently because the updatedObjects set was empty at #3.)
What am I doing wrong? How can I make the MOC realize the re-ordering change?
I fixed this, apparently with a simple solution. I am posting this for future generations of google searchers. :D
The problem is with this line:
(parent.children! as! NSMutableOrderedSet).moveObjects(at: indices, to: to)
Apparently, taking the immutable version and making it mutable works, but doesn't update the managed object. This works:
parent.mutableOrderedSetValue(forKey: "children").moveObjects(at: indices, to: to)

How do you get SwiftUI Previews to work when Codegen is in ClassDefinition or Category/Extension?

I have a view using core data and xcdatamodeld file that contains the definition for an Item struct. If I use Xcode to generate the files for Item and manually manage them, preview works fine. However, when I use Codegen in either of the other formations, I get errors saying that the entire struct is undefined. This prevents the previews from working.
Code:
struct ArchiveView: View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
#FetchRequest(entity: Item.entity(), sortDescriptors: []) var fetchedResults: FetchedResults<Item>
var body: some View {
return NavigationView {
List(fetchedResults, id: \.self ) { (fetchedResult: Item) in
return PurchaseView(name: fetchedResults.name price: fetchedResults.price, purchaseDate: fetchedResults.date)
}
}.navigationBarTitle("Order")
}
}
Both the Item+CoreDataClass and Item+CoreDataProperties are missing since they are automatically generated by xcode.
I am now using manual Codegen to be able to see the previews, but am curious whether I could use the other options. How can I use Class Defintion Codegen for the core data files and still be able to use SwiftUI previews?
After some testing, something appears to be wrong with the xcode code generator itself. Whenever I change the code generator to anything other than Class Definition at least once, this breaks the linking with previews.
The fix was to create a new project and copy over the old files.

Does Core Data bypass security?

My iOS 13.2 Swift app is a type of SceneKit editor which uses Core Data to persist user edits. I'm wondering if Core Data might be associated with the message below since NSManagedObject is a subclass of NSObject and since a test app I created without Core Data does not cause the message to be displayed.
Although I haven't subclassed any SceneKit classes which support NSSecureCoding, and no other classes in the app use NSSecureCoding, the following message is displayed when a SCNScene is displayed in a SCNView:
The Displayed Message:
[general] NSSecureCoding allowed classes list contains [NSObject class], which bypasses security by allowing any Objective-C class to be implicitly decoded. Consider reducing the scope of allowed classes during decoding by listing only the classes you expect to decode, or a more specific base class than NSObject.
This message is displayed only once even though a SCNScene can be reopened multiple times to reflect the user's edits.
Possible Causes
1. Some of the Core Data entities contain binary data properties used to display thumbnail images. However, when I comment-out the code associated with creating/displaying the thumbnails, the above message is still displayed. The thumbnail data is created with the following code which returns an optional data object. I wonder about this, because Swift bridges to NSData which is a subclass of NSObject.
static func createNonCachedItemThumbnailData(item: Item) -> Data? {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let dataSource = appDelegate.dataSource
guard let selectedDesign = dataSource.selectedDesign else { return nil }
let resourceSubdirectoryName = selectedDesign.uniqueID!
guard let bundleURL = Bundle.main.url(forResource: item.uniqueID!, withExtension: "png", subdirectory: resourceSubdirectoryName + ".scnassets") else { return nil }
guard let imageSource = CGImageSourceCreateWithURL(bundleURL as CFURL, nil) else { return nil }
/*
maxDimension is the lesser of the width or height of the UIImageView in ItemSCNNodeSelectionViewCell.
*/
let maxDimension: CGFloat = 64.0
let options: [NSString: Any] = [
kCGImageSourceThumbnailMaxPixelSize: maxDimension,
kCGImageSourceCreateThumbnailFromImageAlways: true]
guard let scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary) else { return nil }
return UIImage(cgImage: scaledImage).pngData()
}
One of the Core Data entities uses NSKeyedArchiver/NSKeyedUnarchiver to archive SCNMaterial as binary data. I didn't use the transformable type for this property, because I read that the transformable type doesn't notice changes when the context is saved. This code seems far from the problem, but the compiler may have noticed it.
Any help would be appreciated.

Haxe - Why can I not access a child's attribute without getting an error that the parent does not have the given attribute?

I've recently been getting into Haxe and just started to use HaxeFlixel to load a Tiled .TMX file.
I am creating a TiledMap object and passing it the TMX file path, then I want to iterate over the layers in that object to add them to the game scene. However when I try to access .tileArray (which is a property of TiledTileLayer) I get the following error :-
flixel.addons.editors.tiled.TiledLayer has no field tileArray
Here is the code:
package;
import flixel.FlxState;
import flixel.tile.FlxTilemap;
import flixel.addons.editors.tiled.TiledMap;
import openfl.Assets;
class PlayState extends FlxState
{
private var _tiled_map:TiledMap;
override public function create():Void
{
_tiled_map = new TiledMap("assets/data/Map1.tmx");
for(layer in _tiled_map.layers){
var layerData:Array<Int> = layer.tileArray;
}
super.create();
}
override public function update(elapsed:Float):Void
{
super.update(elapsed);
}
}
I've found the following example - http://coinflipstudios.com/devblog/?p=182 which seems to work fine for people.
So I wanted to check whether the layer object was a TiledTileLayer as it should be, or TiledLayer, with the following:
trace(Type.typeof(layer));
Which sure enough yields:
PlayState.hx:24: TClass([class TiledTileLayer])
So if it is a TiledTileLayer which has the field tileArray why is it moaning?
I had a look at the source code (https://github.com/HaxeFlixel/flixel-addons/blob/dev/flixel/addons/editors/tiled/TiledMap.hx#L135) and TiledTileLayer inherits from TiledLayer. Layers is an array of type TiledLayer, so I think this is why it is moaning. I can clearly see that the array is storing child objects of TiledLayer, but as soon as I access any props/methods of those children, it complains that the parent does not have that field? Very confusing!
To run I'm using this command: C:\HaxeToolkit\haxe\haxelib.exe run lime test flash -debug -Dfdb
Thank you!
So if it is a TiledTileLayer which has the field tileArray why is it moaning?
It may be a TiledTileLayer in this case, but that may not always be the case. layers is an Array<TileLayer> after all, so it could be a TiledObjectLayer or a TiledImageLayer as well (which don't have a tileArray field). This can nicely be seen in the code you linked. The concrete type can only be known at runtime, but the error you get happens at compile-time.
If you know for sure there won't be any object or image layers, you can just cast it to a TiledTileLayer. However, just to be safe, it's good practice to check the type beforehand anyway:
for (layer in _tiled_map.layers) {
if (Std.is(layer, TiledTileLayer)) {
var tileLayer:TiledTileLayer = cast layer;
var layerData:Array<Int> = tileLayer.tileArray;
}
}
It works without this for the tutorial you linked because it was made for an older version of flixel-addons.

Where is Asp.Net Core source code for EphemeralKeyRing Class?

Was EphemeralKeyRing omitted from GitHub for Security Reasons?
This one is a brain teaser. I've spent quite a bit of time lately reading and and absorbing the hierarchy of classes that relate to asp.net core session storage and asp.net core data protection. In those journeys, I have come across a reference to a EphemeralKeyRing class. However, the code for this class does not seem to be in the Asp.Net Core source code repository on GitHub. Equally odd, when doing a google search on this class name, I can find no references anywhere on the internet that are about this asp.net core class other than the one GitHub source code file that uses it.
Here is the class that news up a EphemeralKeyRing object: https://github.com/aspnet/DataProtection/blob/rel/1.1.0/src/Microsoft.AspNetCore.DataProtection/EphemeralDataProtectionProvider.cs
Here's the results of a GitHub search for the EphemeralKeyRing class in the Asp.Net Core repository:
:
And here is the an amazingly sparse set of google results when searching for EphemeralKeyRing. Note the first entry is the code file on GitHub that I mentioned above which uses the object and the other results are unrelated to this asp.net core class.
So my question is this: Was the source code for the EphemeralKeyRing class omitted from GitHub purposely for security reasons? Or is it there and I'm just searching wrong?
Here is the link:
https://github.com/aspnet/DataProtection/blob/master/src/Microsoft.AspNetCore.DataProtection/EphemeralDataProtectionProvider.cs
which I see you found and clicked on it already. If you go to the bottom of the page youll see the class you are looking for, I'll paste the code just in case:
private sealed class EphemeralKeyRing<T> : IKeyRing, IKeyRingProvider
where T : IInternalAuthenticatedEncryptionSettings, new()
{
// Currently hardcoded to a 512-bit KDK.
private const int NUM_BYTES_IN_KDK = 512 / 8;
public IAuthenticatedEncryptor DefaultAuthenticatedEncryptor { get; } = new T().ToConfiguration(services: null).CreateNewDescriptor().CreateEncryptorInstance();
public Guid DefaultKeyId { get; } = default(Guid);
public IAuthenticatedEncryptor GetAuthenticatedEncryptorByKeyId(Guid keyId, out bool isRevoked)
{
isRevoked = false;
return (keyId == default(Guid)) ? DefaultAuthenticatedEncryptor : null;
}
public IKeyRing GetCurrentKeyRing()
{
return this;
}
}

Resources