Post

Replies

Boosts

Views

Activity

NSManagedObjectContextDidSave has old data
My app uses CoreData to locally cache data from other services (3rd party, CloudKit). To simplify the logic of when I send changes from the app back to the service I use a notification listening for `NSManagedObjectContextDidSave`.```NotificationCenter.default.addObserver(forName: .NSManagedObjectContextDidSave, object: nil, queue: nil) { [weak self] notification in guard let welf = self, let userInfo = notification.userInfo, let context = notification.object as? NSManagedObjectContext, context.parent == nil else { return } if let shouldSync = context.userInfo["ShouldSync"] as? Bool, !shouldSync { return } let syncContext = welf.coreDataStack.newPrivateContext() syncContext.name = "SyncContext" syncContext.perform { syncContext.userInfo["ShouldSync"] = false let inserted = welf.objectsForKey(NSInsertedObjectsKey, dictionary: userInfo as NSDictionary, context: syncContext) let updated = welf.objectsForKey(NSUpdatedObjectsKey, dictionary: userInfo as NSDictionary, context: syncContext) let deleted = welf.objectsForKey(NSDeletedObjectsKey, dictionary: userInfo as NSDictionary, context: syncContext) welf.syncManager.store(inserted, updated: updated, deleted: deleted, context: syncContext) } }```I use `ShouldSync` user info to easily ignore trying to save the changes made by `syncManager.store` which flip flags on objects to mark them as up to date or not.```public func newPrivateContext() -> NSManagedObjectContext { let newPrivateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) newPrivateContext.persistentStoreCoordinator = storeContainer.persistentStoreCoordinator newPrivateContext.name = "New private context" newPrivateContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) return newPrivateContext }```This is the new context I create, simply so I can add the `ShouldSync` user info without changing the context I use throughout the app and UI.Anyways, I'm seeing some weird behavior where I flip the sync flag `object.hasSynced = false` to start syncing and when I check the `userInfo` and the contexts `registeredObjects` in `NSManagedObjectContextDidSave` notification block I see `hasSynced = true`.How can I debug / fix this? The only method that sets `hasSynced` to true is creating the objects from the server, and within `syncManager.store(...)` so I don't think this is a problem of setting it to false and then back to true.
1
0
999
Apr ’20
WidgetKit custom DateFormatter
I'd like to display the number of days til a date inside of a widget, such as "2 days", but when I get to 1 day I want to have it say "Tomorrow", and on the same date to display the time "8:00 PM". I'm currently doing this by getting the number of days between the current date and second date and switching on that number, and creating a new label with different strings. Because widgets don't update automatically I'll have to refresh my widget every day at midnight to have the label re-calculate. Can I get this same functionality with existing formatters, or subclass DateFormatter myself and have the label refresh periodically as when using Text(date, style: ...)? I did try subclassing DateFormatter and override string(from:) → String but the text doesn't appear.
0
0
874
Oct ’20
Widget not refreshing on date
I want to refresh my widget every day at midnight. I'm getting the date with let currentDate = Date() let midnight = Calendar.current.startOfDay(for: currentDate) let nextMidnight = Calendar.current.date(byAdding: .day, value: 1, to: midnight)! and passing it to my TimeLine completion(Timeline(entries: entries, policy: .after(nextMidnight))) but when I reach this date, my widget doesn't refresh. I've also received reports from Testflight users of my app that say they see a "-1 Day" label in my widget, which sounds like the view of the widget refreshed before fetching a new timeline with an entry for the next day. I tested widget refresh from actually being up til after midnight, and by changing the clock on the phone to 11:5X and waiting, never seeing a change or code executed when attached to Xcode.
1
0
937
Oct ’20
fileImporter download progress from files in iCloud Drive
I'm using fileImporter for a Mac app. If I open a file from iCloud Drive that isn't already downloaded, I need to start the download before I can read the contents of the file. I found that I can download the file by using NSFileCoordinator or FileManager.default.startDownloadingUbiquitousItem. These APIs will begin the download, but I have no updates on the progress or if the file has been downloaded. I've tried to use NSMetadataQuery with no luck. Is there a way, either with fileImporter in SwiftUI or an AppKit API that I can receive updates for when a remote file has been downloaded, or do I need to prompt the users to download the file themselves before importing into my app?
1
1
1.4k
Sep ’21
Table view cell focus effect appears on touch
Some of the table views in my application are showing a focus effect when touching the screen. From my understanding and using Apple’s apps and samples, the focus effect should only appear when using the keyboard for navigation. I can’t figure out how to disable the focus effect for touches without disabling keyboard navigation entirely though. I have another table view, that is set up in an almost identical way but with a different cell layout, but never shows a focus effect even with the keyboard, although I can see the table scroll as I press the arrow down key. I haven’t started implementing any custom focus code yet. I just build the app with Xcode 13 and dropped support for iOS 13. Any help is appreciated!
0
0
822
Oct ’21
macOS 12.3 erasing documents folder on boot
I updated to the 12.3 beta the other day (by accident, I didn't realize or know how I ended up in the beta program for Mac), and I realized my Documents folder was empty. I thought perhaps it is a visual glitch and put another file in there, then rebooted, and that file is now missing too on reboot. Spotlight and Finder can't find any of the missing files so I believe they're being deleted on reboot now. Hope this is fixed soon.
1
0
715
Feb ’22
`SecItemAdd` showing error on macOS
I'm using the library KeychainAccess to save a token in the keychain. For some reason I'm getting an error when SecItemAdd is called, presenting a system dialogue saying "Keychain not found" "A keychain cannot be found to store "token." and a button to "Reset to Defaults" which shows another alert "Are you sure you want to reset your keychain? This will delete all your saved passwords, keys, and certificates. You cannot undo this operation." The same code is working for many others on my team, and others using this library. I can't find much on this error. Is there a way to fix without reseting my personal keychain?
0
1
776
Jul ’22
NSView support delete key and menu bar item
I have an app using both AppKit and SwiftUI. In SwiftUI I can use the code below to activate the delete action under edit and the Mac "invalid key" tone doesn't sound. I can't figure out how to support this behavior in AppKit though. I have a view that is the first responder, and added the code below: SwiftUI view: .onDeleteCommand { ... } AppKit: override func deleteBackward(_ sender: Any?) {         super.deleteBackward(sender)     } but it is never called. I also tried override func responds(to aSelector: Selector!) -> Bool { but it doesn't work either. How can I support this?
0
0
694
Oct ’22
NSView set the key-loop for subviews only
I want to use the default key-loop calculation for most of my app except one view, where the views have a specific numbered order but visually are not left to right, top to bottom. when using the windows automatic key-loop setup, setting nextKeyView gets override it appears. I can override the property and return the next view, but then there are issues with leaving the loop now. When the last item has focus, the next key view should be the top-most view to the right, but instead it gets stuck. And shift-tabbing backwards goes to the last item before entering the key-view loop. Is there a best practice and example of how to do this?
0
0
707
Oct ’22
How to show dock menu for Catalyst apps?
I've added Mac support to my iOS app and would like to add menu items when right clicking on the app icon. I was already using app shortcuts on iOS. I have a static item defined in my info.plist under the UIApplicationShortcutItems key. and I have dynamic actions I setup in applicationWillEnterForeground. Sometimes these actions appear when right clicking the app icon but most of the time they don't. Is there an example project or best practice to get this working?
1
0
1.1k
Nov ’22
CoreData migration object duplicated
During migration one object is being duplicated for an unknown reason, and its relationships are not set causing migration to fail since the relationship is required. I have no idea why this object is being duplicated though. I would expect the same number of objects for all entities to exist after the migration as they did before. I have an entity TVShow, that I renamed a relationship from cast to characters, and added a new attribute genre. I have a custom migration policy that sets the genre attribute. I created a mapping model, set the custom policy for TVShowToTVShow and left everything else alone. A single TVSeason object is duplicated though after the migration, and doesn't have its show relationship set on the duplicate only. I have no idea why it was duplicated though. The TVShow wasn't. I have a possible fix for now by fetching the new object and deleting it, but I don't want to have to include this in every migration going forward if I can't tell the cause of it in the first place. My custom TVShow policy is: class TVShowToTVShowMigrationPolicy_172_to_192: NSEntityMigrationPolicy {     override func createRelationships(forDestination dInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws {         try super.createRelationships(forDestination: dInstance, in: mapping, manager: manager)                  guard dInstance.value(forKey: "genre") == nil else {             print("genre already set")             return         }                  // set `genre` to the first item in `genres`         if let genres = dInstance.value(forKey: "genres") as? Set<NSManagedObject> {             dInstance.setValue(genres.first, forKey: "genre")         } else {             print("No genres found")         }     } } and the new policy I created to remove the duplicate is class TVSeasonToTVSeasonMigrationPolicy_172_to_192: NSEntityMigrationPolicy {     override func endRelationshipCreation(forMapping mapping: NSEntityMapping, manager: NSMigrationManager) throws {         try super.endRelationshipCreation(forMapping: mapping, manager: manager)         print(#function)                  let dContext = manager.destinationContext         let request: NSFetchRequest<NSManagedObject> = NSFetchRequest<NSManagedObject>(entityName: "TVSeason")         request.predicate = NSPredicate(format: "%K == nil", #keyPath(TVSeason.show))         let seasons = try dContext.fetch(request)         print(seasons)         for season in seasons {             dContext.delete(season)         }     } } Is this potentially a CoreData issue and I should just go with the de-duplicate policy, or is there anything I can do to prevent the duplicate from existing in the first place? I am not using CloudKit which I've read has a similar issue.
1
0
878
Dec ’22
Xcode "Build documentation" not working with Swift Macro package in project
I have a workspace with my project and a Swift Macro. When I use the "Build Documentation" command the build fails with this error: fatal error: module map file '/Users/me/Library/Developer/Xcode/DerivedData/Project-fmdkuqlofexbqdhhitpgjnoqzyrz/Build/Intermediates.noindex/GeneratedModuleMaps-iphoneos/Macros.modulemap' not found Is there a way around this?
2
1
754
Feb ’24