Bring Core Data concurrency to Swift and SwiftUI

RSS for tag

Discuss the WWDC21 session Bring Core Data concurrency to Swift and SwiftUI.

Posts under wwdc21-10017 tag

10 Posts

Post

Replies

Boosts

Views

Activity

form top row
how do i get rid of this grey top row?  var body: some View {           NavigationView {     Form {       HStack {         Form {                      TextField("pH", text: $viewModel.pH)             .modifier(TextFieldClearButton(text: $viewModel.pH))           TextField("pCO2", text: $viewModel.pCO2)             .modifier(TextFieldClearButton(text: $viewModel.pCO2))                       TextField("HCO3", text: $viewModel.HCO3)             .modifier(TextFieldClearButton(text: $viewModel.HCO3))           TextField("Glu", text: $viewModel.Glu)             .modifier(TextFieldClearButton(text: $viewModel.Glu))                       Spacer()                             }.frame(width: /*@START_MENU_TOKEN@*/150.0/*@END_MENU_TOKEN@*/, height: 200).lineSpacing(/*@START_MENU_TOKEN@*/5.0/*@END_MENU_TOKEN@*/)                 Form {                       TextField("Na", text: $viewModel.Na)              .modifier(TextFieldClearButton(text: $viewModel.Na))            TextField("K", text: $viewModel.K)              .modifier(TextFieldClearButton(text: $viewModel.K))            TextField("Cl", text: $viewModel.Cl)              .modifier(TextFieldClearButton(text: $viewModel.Cl))            TextField("Alb", text: $viewModel.Alb)              .modifier(TextFieldClearButton(text: $viewModel.Alb))                     }.frame(width: /*@START_MENU_TOKEN@*/150.0/*@END_MENU_TOKEN@*/, height: /*@START_MENU_TOKEN@*/200.0/*@END_MENU_TOKEN@*/)          .lineSpacing(/*@START_MENU_TOKEN@*/5.0/*@END_MENU_TOKEN@*/)
1
0
680
May ’22
In coredata and swiftUI, how can I get the objects that are related to an object that is related to the object I have
I have 3 entities: Topic, Group and Word. Topic has a one-to-many relation with Group, and Group has a one-to-many relation with Word. From a list of words, I want to get the ones that belong to certain topic. That means, getting the group of the word and then the topic of the word. For a Word fetch request, I have NSPredicate(format: "group.topic = %@", topic). Where topic is the object I want to match word to. But this isn't working so I guess it isn't the right way of doing it. Does someone know how something like this could be done?
1
0
613
May ’22
CoreData: NSPredicate sometimes gives empty lists with SwiftUI
I'm having problems with NSPredicate. It started because for some conditions I got empty lists when I knew there was something in the model. I've made a lot of tests and I found that it fails when I use %@ (to have a variable). If I write the variable directly, it works fine. But in some situations, it works fine when I have a %@, but if I add a second variable with AND it gives again an empty list. I've checked that the context, the spelling are fine. Also, the objects do exist, since I get them by typing the variable directly. For some reason, I get an empty list in some situation (which are always the same situations, it doesn't happen randomly). I think the problem is that CoreData gives and error, so I get an empty list as the default. Does anyone know what could be happening?
1
0
678
Apr ’22
CoreData concurrency debug
I am using a database with NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) Everything works fine, I save objects, read, and delete without problems. If set "-com.apple.CoreData.ConcurrencyDebug 1" : I save the object through the PerformAndWait block - ok I do fetch - receive an object, but its properties are empty (data = fault) and it crashes. (EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)) sample code: public final class  DatabaseCore {     private let persistentContainer: NSPersistentContainer     private var backgroundContext: NSManagedObjectContext!     private let queue: DispatchQueue public init() {         self.persistentContainer = Self.createPersistentContainer()         self.queue = queue         self.queue.async {             self.backgroundContext = Self.createNewBackgroundContext(container: self.persistentContainer)         } // Private     private static func createPersistentContainer() -> NSPersistentContainer {         let model = NSManagedObjectModel(contentsOf: Bundle.module.url(forResource: "TestModel", withExtension: "momd")!)         let container = NSPersistentContainer(name: "TestModel", managedObjectModel: model)         let description = NSPersistentStoreDescription()         description.url = URL(fileURLWithPath: "/dev/null")         container.persistentStoreDescriptions = [description]         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                // print error             }         })         return container     } private static func createNewBackgroundContext(container: NSPersistentContainer) -> NSManagedObjectContext {         let context = container.newBackgroundContext()         context.mergePolicy = NSOverwriteMergePolicy         context.undoManager = nil         return context     } private static func saveContext(_ context: NSManagedObjectContext) {         context.performAndWait {             if !context.hasChanges { return }             do {                 try context.save()             } catch {                 // print error             }         }     } // Public public func upsert(_ block: @escaping (NSManagedObjectContext) -> Void, completion: (() -> Void)?) {         self.queue.async {             let context: NSManagedObjectContext! = self.backgroundContext             self.backgroundContext.performAndWait {                 block(context)                 Self.saveContext(context)             }             completion?()         }     } public func fetch<ResultType: NSFetchRequestResult>(_ request: NSFetchRequest<ResultType>, completion: @escaping ([ResultType]) -> Void) {         self.queue.async {             var result: [ResultType] = []             self.backgroundContext.performAndWait {                 do {                     result = try request.execute()                 } catch let error {                     // print error                 }             }             completion(result)         }     } } I set a breakpoint to result fetch func if set  "-com.apple.CoreData.ConcurrencyDebug 1": (lldb) po record <Test: 0x7b1400030070> (entity: Test; id: 0xbb200e8d680f1045 <x-coredata://1BFC3A95-3F7D-4A23-AD20-FDF23B575D73/CDLog/p1>; data: <fault>) (lldb) po record.value error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). The process has been returned to the state before expression evaluation. Without  "-com.apple.CoreData.ConcurrencyDebug 1", everything works correctly, without a crash. (lldb) po record <Test: 0x7b1400028c80> (entity: Test; id: 0xb29880bd32a57757 <x-coredata://1BFC3A95-3F7D-4A23-AD20-FDF23B575D73/CDLog/p1>; data: <fault>) (lldb) po record.value 0 How can this be fixed? Thank you! =) Xcode 13.3
1
0
2.8k
Apr ’22
Missing SortMenu in the example code
I'm not sure if I'm missing something but the SortMenu view to which Scott inserted a reference at around 21:17 isn't shown anywhere in the video, nor is it part of the downloadable source code. I'd like to reproduce the sort menu shown in this example but it's strange that the code differs from the video that much.
0
0
1.1k
Apr ’22
Failing to migrate and update CoreData to widget extension
I have a CoreData database, and I have attempted to migrate it to an app group to share it between my main app and a widget extension. The database seems that seems to be fetched by the app and the widget seem to be completely separate from each other. My CoreData code (persistence.swift) import CoreData struct PersistenceController {   static let shared = PersistenceController()   static var preview: PersistenceController = {     let result = PersistenceController(inMemory: true)     let viewContext = result.container.viewContext     let newUserData = Userdata(context: viewContext)     newUserData.hourly = 15.3     let newSession = Session(context: viewContext)     newSession.id = UUID()     newSession.start = Date()     newSession.end = Date()     do {       try viewContext.save()     } catch {       let nsError = error as NSError       fatalError("Unresolved error \(nsError), \(nsError.userInfo)")     }     return result   }()   let container: NSPersistentContainer   init(inMemory: Bool = false) {     container = NSPersistentContainer(name: "FManger")     let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.omaribrahim-uchicago.FManger")!.appendingPathComponent("FManger.sqlite")     var defaultURL: URL?       if let storeDescription = container.persistentStoreDescriptions.first, let url = storeDescription.url {         defaultURL = FileManager.default.fileExists(atPath: url.path) ? url : nil       }     if defaultURL == nil {         container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeURL)]       }     container.loadPersistentStores(completionHandler: { [unowned container] (storeDescription, error) in         if let error = error as NSError? {           fatalError("Unresolved error \(error), \(error.userInfo)")         }         if let url = defaultURL, url.absoluteString != storeURL.absoluteString {           let coordinator = container.persistentStoreCoordinator           if let oldStore = coordinator.persistentStore(for: url) {             do {               try coordinator.migratePersistentStore(oldStore, to: storeURL, options: nil, withType: NSSQLiteStoreType)             } catch {               print(error.localizedDescription)             }             // delete old store             let fileCoordinator = NSFileCoordinator(filePresenter: nil)             fileCoordinator.coordinate(writingItemAt: url, options: .forDeleting, error: nil, byAccessor: { url in               do {                 try FileManager.default.removeItem(at: url)               } catch {                 print(error.localizedDescription)               }             })           }         }       })   } } My Widget data constructor and main function import WidgetKit import SwiftUI import Intents struct Provider: IntentTimelineProvider {       func placeholder(in context: Context) -> SimpleEntry {     SimpleEntry(date: Date(), data: .previewData, error: false, configuration: ConfigurationIntent())   }   func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {     let entry = SimpleEntry(date: Date(), data: .previewData, error: false, configuration: configuration)           completion(entry)   }   func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {     var entries: [SimpleEntry] = []     @FetchRequest(       sortDescriptors:[NSSortDescriptor(key: "start", ascending: false)],       animation: .default)     var sessions: FetchedResults<Session>           if (sessions.count > 0) {       let checkedIn = sessions[0].end != nil       let totalMinutes = totalMinutes(sessions: sessions)       var auxMinutes = 0.0       if (checkedIn) {         auxMinutes = timeBetween(fromDate: sessions[0].start!, toDate: Date())       }               let currentDate = Date()       for i in 0 ..< 5 {         let entryDate = Calendar.current.date(byAdding: .hour, value: i, to: currentDate)!                   let cSession = fromMinutes(minutes: (Double(i) * 60) + auxMinutes)                   let widgetData = SimpleEntry.PayData(currentSession: cSession,                            grossTotal: totalMinutes * 15.3 + cSession,                            paycheckDay: Date() + (7 * 24 * 60 * 60),                            checkedIn: checkedIn)                   let entry = SimpleEntry(date: entryDate,                     data: widgetData,                     error: false,                     configuration: configuration)                   entries.append(entry)       }     }     else {       let entry = SimpleEntry(date: Date(),                   data: .error,                   error: true,                   configuration: configuration)       entries.append(entry)     }     let timeline = Timeline(entries: entries, policy: .atEnd)     completion(timeline)   } } @main struct Widgets: Widget {   let kind: String = "Widgets"   let persistenceController = PersistenceController.shared   var body: some WidgetConfiguration {     IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in       WidgetsEntryView(entry: entry)         .environment(\.managedObjectContext, persistenceController.container.viewContext)     }     .configurationDisplayName("Pay Tracker")     .description("Check your current shift's earning, total earnings, and the date of your next payment in a glance.")   } } I am pretty sure I did something wrong, but what is it?
0
0
1.2k
Mar ’22
Swift 5.5 Concurrency: how to serialize async Tasks to replace an OperationQueue with maxConcurrentOperationCount = 1?
I’m currently migrating my app to use the concurrency model in Swift. I want to serialize Tasks to make sure they are executed one after the other (no paralellism). In my use case, I want to listen to notifications posted by the NotificationCenter and execute a Task every time a new notification is posted. But I want to make sure no previous task is running. It's the equivalent of using an OperationQueue with maxConcurrentOperationCount = 1. For example, I’m using CloudKit with Core Data in my app and I use persistent history tracking to determine what changes have occurred in the store. In this Synchronizing a Local Store to the Cloud Sample Code, Apple uses an operation queue for handling history processing tasks (in CoreDataStack). This OperationQueue has a maximum number of operations set to 1. private lazy var historyQueue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 return queue }() When a Core Data notification is received, a new task is added to this serial operation queue. So if many notifications are received, they will all be performed one after the other one in a serial way. @objc func storeRemoteChange(_ notification: Notification) { // Process persistent history to merge changes from other coordinators. historyQueue.addOperation { self.processPersistentHistory() } } In this Loading and Displaying a Large Data Feed Sample Code, Apple uses Tasks to handle history changes (in QuakesProvider). // Observe Core Data remote change notifications on the queue where the changes were made. notificationToken = NotificationCenter.default.addObserver(forName: .NSPersistentStoreRemoteChange, object: nil, queue: nil) { note in Task { await self.fetchPersistentHistory() } } I feel something is wrong in the second project as Tasks could happen in any order, and not necessarily in a serial order (contrary to the first project where the OperationQueue as a maxConcurrentOperationCount = 1). Should we use an actor somewhere to make sure the methods are serially called? I thought about an implementation like this but I’m not yet really comfortable with that: actor PersistenceStoreListener { let historyTokenManager: PersistenceHistoryTokenManager = .init() private let persistentContainer: NSPersistentContainer init(persistentContainer: NSPersistentContainer) { self.persistentContainer = persistentContainer } func processRemoteStoreChange() async { print("\(#function) called on \(Date.now.formatted(date: .abbreviated, time: .standard)).") } } where the processRemoteStoreChange method would be called by when a new notification is received (AsyncSequence): notificationListenerTask = Task { let notifications = NotificationCenter.default.notifications(named: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator) for await _ in notifications { print("notificationListenerTask called on \(Date.now.formatted(date: .abbreviated, time: .standard)).") await self.storeListener?.processRemoteStoreChange() } }
1
0
5.9k
Mar ’22
Delay contextMenu on SwiftUI
I'm trying to delay when the contextMenu appears because I have a drag gesture over the same view which causes a confuse user experience. My code: … Text(exampleText) .contextMenu { delay() // Menus here } .gesture( DragGesture() .onEnded( { end in switch exampleTextAlignment { case .leading: if end.translation.width > 0 { exampleTextAlignment = .center onContextMenuAlignment = .top } case .center: if end.translation.width < 0 { exampleTextAlignment = .leading onContextMenuAlignment = .topLeading } else if end.translation.width > 0 { exampleTextAlignment = .trailing onContextMenuAlignment = .topTrailing } case .trailing: if end.translation.width < 0 { exampleTextAlignment = .center onContextMenuAlignment = .top } } } ) ) … where delay() is: … private func delay() async { try? await Task.sleep(nanoseconds: UInt64(secondsHere * Double(NSEC_PER_SEC))) hasTimeElapsed = true } … Xcode v.13.2 and iOS v.15.2. Here's a more detailed question: https://stackoverflow.com/questions/71201562/delay-contextmenu-on-swiftui
0
0
1.3k
Feb ’22
SectionedFetchRequest mixes up the sections
I am presenting a list of Items which are sections by the categoryIdentifier property. My app uses CloudKit. When I add change the categoryIdentifier for an item it is display in the correct section and other running instances of the app do the same. When restarting the app some items are grouped under an incorrect section, but the cstegoryIdentifier within the item is still as it was set. My question is what I'm doing wrong that upon restart the organization is incorrect. In case it matters, I'm setting this in the container:         container.viewContext.automaticallyMergesChangesFromParent = true As an aside: It seems necessary to make the sectioning type optional (as is the case in the underlying entity) like this SectionedFetchResults<String?, Item> Though the examples don't seem to need this. struct ContentView: View {     @Environment(\.managedObjectContext) private var viewContext     @State private var isShowingItem = false     @State private var isAddingItem = false          @SectionedFetchRequest(         sectionIdentifier: \.categoryIdentifier,         sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: true)],         animation: .default) private var sectionedItems: SectionedFetchResults<String?, Item>          var body: some View {         NavigationView {             List {                 ForEach(sectionedItems) { section in                     Section(header: Text(Category.nameForId(section.id, context: viewContext)).font(.headline)) {                         ForEach(section) { item in                             NavigationLink(destination: ItemInputView(item: item, category: Category.get(identifier: item.category, context: viewContext))) {                                 Text(item.getName())                             }                         }                     }                 }             }                          .navigationTitle("Foo")             .sheet(isPresented: $isAddingItem) {                 ItemInputView(item: nil, category: Category.getDefault(context: viewContext))             }         }         .navigationViewStyle(.stack)     } }
1
0
1.3k
Jan ’22
form top row
how do i get rid of this grey top row?  var body: some View {           NavigationView {     Form {       HStack {         Form {                      TextField("pH", text: $viewModel.pH)             .modifier(TextFieldClearButton(text: $viewModel.pH))           TextField("pCO2", text: $viewModel.pCO2)             .modifier(TextFieldClearButton(text: $viewModel.pCO2))                       TextField("HCO3", text: $viewModel.HCO3)             .modifier(TextFieldClearButton(text: $viewModel.HCO3))           TextField("Glu", text: $viewModel.Glu)             .modifier(TextFieldClearButton(text: $viewModel.Glu))                       Spacer()                             }.frame(width: /*@START_MENU_TOKEN@*/150.0/*@END_MENU_TOKEN@*/, height: 200).lineSpacing(/*@START_MENU_TOKEN@*/5.0/*@END_MENU_TOKEN@*/)                 Form {                       TextField("Na", text: $viewModel.Na)              .modifier(TextFieldClearButton(text: $viewModel.Na))            TextField("K", text: $viewModel.K)              .modifier(TextFieldClearButton(text: $viewModel.K))            TextField("Cl", text: $viewModel.Cl)              .modifier(TextFieldClearButton(text: $viewModel.Cl))            TextField("Alb", text: $viewModel.Alb)              .modifier(TextFieldClearButton(text: $viewModel.Alb))                     }.frame(width: /*@START_MENU_TOKEN@*/150.0/*@END_MENU_TOKEN@*/, height: /*@START_MENU_TOKEN@*/200.0/*@END_MENU_TOKEN@*/)          .lineSpacing(/*@START_MENU_TOKEN@*/5.0/*@END_MENU_TOKEN@*/)
Replies
1
Boosts
0
Views
680
Activity
May ’22
In coredata and swiftUI, how can I get the objects that are related to an object that is related to the object I have
I have 3 entities: Topic, Group and Word. Topic has a one-to-many relation with Group, and Group has a one-to-many relation with Word. From a list of words, I want to get the ones that belong to certain topic. That means, getting the group of the word and then the topic of the word. For a Word fetch request, I have NSPredicate(format: "group.topic = %@", topic). Where topic is the object I want to match word to. But this isn't working so I guess it isn't the right way of doing it. Does someone know how something like this could be done?
Replies
1
Boosts
0
Views
613
Activity
May ’22
CoreData: NSPredicate sometimes gives empty lists with SwiftUI
I'm having problems with NSPredicate. It started because for some conditions I got empty lists when I knew there was something in the model. I've made a lot of tests and I found that it fails when I use %@ (to have a variable). If I write the variable directly, it works fine. But in some situations, it works fine when I have a %@, but if I add a second variable with AND it gives again an empty list. I've checked that the context, the spelling are fine. Also, the objects do exist, since I get them by typing the variable directly. For some reason, I get an empty list in some situation (which are always the same situations, it doesn't happen randomly). I think the problem is that CoreData gives and error, so I get an empty list as the default. Does anyone know what could be happening?
Replies
1
Boosts
0
Views
678
Activity
Apr ’22
CoreData concurrency debug
I am using a database with NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) Everything works fine, I save objects, read, and delete without problems. If set "-com.apple.CoreData.ConcurrencyDebug 1" : I save the object through the PerformAndWait block - ok I do fetch - receive an object, but its properties are empty (data = fault) and it crashes. (EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)) sample code: public final class  DatabaseCore {     private let persistentContainer: NSPersistentContainer     private var backgroundContext: NSManagedObjectContext!     private let queue: DispatchQueue public init() {         self.persistentContainer = Self.createPersistentContainer()         self.queue = queue         self.queue.async {             self.backgroundContext = Self.createNewBackgroundContext(container: self.persistentContainer)         } // Private     private static func createPersistentContainer() -&gt; NSPersistentContainer {         let model = NSManagedObjectModel(contentsOf: Bundle.module.url(forResource: "TestModel", withExtension: "momd")!)         let container = NSPersistentContainer(name: "TestModel", managedObjectModel: model)         let description = NSPersistentStoreDescription()         description.url = URL(fileURLWithPath: "/dev/null")         container.persistentStoreDescriptions = [description]         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                // print error             }         })         return container     } private static func createNewBackgroundContext(container: NSPersistentContainer) -&gt; NSManagedObjectContext {         let context = container.newBackgroundContext()         context.mergePolicy = NSOverwriteMergePolicy         context.undoManager = nil         return context     } private static func saveContext(_ context: NSManagedObjectContext) {         context.performAndWait {             if !context.hasChanges { return }             do {                 try context.save()             } catch {                 // print error             }         }     } // Public public func upsert(_ block: @escaping (NSManagedObjectContext) -&gt; Void, completion: (() -&gt; Void)?) {         self.queue.async {             let context: NSManagedObjectContext! = self.backgroundContext             self.backgroundContext.performAndWait {                 block(context)                 Self.saveContext(context)             }             completion?()         }     } public func fetch&lt;ResultType: NSFetchRequestResult&gt;(_ request: NSFetchRequest&lt;ResultType&gt;, completion: @escaping ([ResultType]) -&gt; Void) {         self.queue.async {             var result: [ResultType] = []             self.backgroundContext.performAndWait {                 do {                     result = try request.execute()                 } catch let error {                     // print error                 }             }             completion(result)         }     } } I set a breakpoint to result fetch func if set  "-com.apple.CoreData.ConcurrencyDebug 1": (lldb) po record &lt;Test: 0x7b1400030070&gt; (entity: Test; id: 0xbb200e8d680f1045 &lt;x-coredata://1BFC3A95-3F7D-4A23-AD20-FDF23B575D73/CDLog/p1&gt;; data: &lt;fault&gt;) (lldb) po record.value error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). The process has been returned to the state before expression evaluation. Without  "-com.apple.CoreData.ConcurrencyDebug 1", everything works correctly, without a crash. (lldb) po record &lt;Test: 0x7b1400028c80&gt; (entity: Test; id: 0xb29880bd32a57757 &lt;x-coredata://1BFC3A95-3F7D-4A23-AD20-FDF23B575D73/CDLog/p1&gt;; data: &lt;fault&gt;) (lldb) po record.value 0 How can this be fixed? Thank you! =) Xcode 13.3
Replies
1
Boosts
0
Views
2.8k
Activity
Apr ’22
Missing SortMenu in the example code
I'm not sure if I'm missing something but the SortMenu view to which Scott inserted a reference at around 21:17 isn't shown anywhere in the video, nor is it part of the downloadable source code. I'd like to reproduce the sort menu shown in this example but it's strange that the code differs from the video that much.
Replies
0
Boosts
0
Views
1.1k
Activity
Apr ’22
Failing to migrate and update CoreData to widget extension
I have a CoreData database, and I have attempted to migrate it to an app group to share it between my main app and a widget extension. The database seems that seems to be fetched by the app and the widget seem to be completely separate from each other. My CoreData code (persistence.swift) import CoreData struct PersistenceController {   static let shared = PersistenceController()   static var preview: PersistenceController = {     let result = PersistenceController(inMemory: true)     let viewContext = result.container.viewContext     let newUserData = Userdata(context: viewContext)     newUserData.hourly = 15.3     let newSession = Session(context: viewContext)     newSession.id = UUID()     newSession.start = Date()     newSession.end = Date()     do {       try viewContext.save()     } catch {       let nsError = error as NSError       fatalError("Unresolved error \(nsError), \(nsError.userInfo)")     }     return result   }()   let container: NSPersistentContainer   init(inMemory: Bool = false) {     container = NSPersistentContainer(name: "FManger")     let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.omaribrahim-uchicago.FManger")!.appendingPathComponent("FManger.sqlite")     var defaultURL: URL?       if let storeDescription = container.persistentStoreDescriptions.first, let url = storeDescription.url {         defaultURL = FileManager.default.fileExists(atPath: url.path) ? url : nil       }     if defaultURL == nil {         container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeURL)]       }     container.loadPersistentStores(completionHandler: { [unowned container] (storeDescription, error) in         if let error = error as NSError? {           fatalError("Unresolved error \(error), \(error.userInfo)")         }         if let url = defaultURL, url.absoluteString != storeURL.absoluteString {           let coordinator = container.persistentStoreCoordinator           if let oldStore = coordinator.persistentStore(for: url) {             do {               try coordinator.migratePersistentStore(oldStore, to: storeURL, options: nil, withType: NSSQLiteStoreType)             } catch {               print(error.localizedDescription)             }             // delete old store             let fileCoordinator = NSFileCoordinator(filePresenter: nil)             fileCoordinator.coordinate(writingItemAt: url, options: .forDeleting, error: nil, byAccessor: { url in               do {                 try FileManager.default.removeItem(at: url)               } catch {                 print(error.localizedDescription)               }             })           }         }       })   } } My Widget data constructor and main function import WidgetKit import SwiftUI import Intents struct Provider: IntentTimelineProvider {       func placeholder(in context: Context) -> SimpleEntry {     SimpleEntry(date: Date(), data: .previewData, error: false, configuration: ConfigurationIntent())   }   func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {     let entry = SimpleEntry(date: Date(), data: .previewData, error: false, configuration: configuration)           completion(entry)   }   func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {     var entries: [SimpleEntry] = []     @FetchRequest(       sortDescriptors:[NSSortDescriptor(key: "start", ascending: false)],       animation: .default)     var sessions: FetchedResults<Session>           if (sessions.count > 0) {       let checkedIn = sessions[0].end != nil       let totalMinutes = totalMinutes(sessions: sessions)       var auxMinutes = 0.0       if (checkedIn) {         auxMinutes = timeBetween(fromDate: sessions[0].start!, toDate: Date())       }               let currentDate = Date()       for i in 0 ..< 5 {         let entryDate = Calendar.current.date(byAdding: .hour, value: i, to: currentDate)!                   let cSession = fromMinutes(minutes: (Double(i) * 60) + auxMinutes)                   let widgetData = SimpleEntry.PayData(currentSession: cSession,                            grossTotal: totalMinutes * 15.3 + cSession,                            paycheckDay: Date() + (7 * 24 * 60 * 60),                            checkedIn: checkedIn)                   let entry = SimpleEntry(date: entryDate,                     data: widgetData,                     error: false,                     configuration: configuration)                   entries.append(entry)       }     }     else {       let entry = SimpleEntry(date: Date(),                   data: .error,                   error: true,                   configuration: configuration)       entries.append(entry)     }     let timeline = Timeline(entries: entries, policy: .atEnd)     completion(timeline)   } } @main struct Widgets: Widget {   let kind: String = "Widgets"   let persistenceController = PersistenceController.shared   var body: some WidgetConfiguration {     IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in       WidgetsEntryView(entry: entry)         .environment(\.managedObjectContext, persistenceController.container.viewContext)     }     .configurationDisplayName("Pay Tracker")     .description("Check your current shift's earning, total earnings, and the date of your next payment in a glance.")   } } I am pretty sure I did something wrong, but what is it?
Replies
0
Boosts
0
Views
1.2k
Activity
Mar ’22
Swift 5.5 Concurrency: how to serialize async Tasks to replace an OperationQueue with maxConcurrentOperationCount = 1?
I’m currently migrating my app to use the concurrency model in Swift. I want to serialize Tasks to make sure they are executed one after the other (no paralellism). In my use case, I want to listen to notifications posted by the NotificationCenter and execute a Task every time a new notification is posted. But I want to make sure no previous task is running. It's the equivalent of using an OperationQueue with maxConcurrentOperationCount = 1. For example, I’m using CloudKit with Core Data in my app and I use persistent history tracking to determine what changes have occurred in the store. In this Synchronizing a Local Store to the Cloud Sample Code, Apple uses an operation queue for handling history processing tasks (in CoreDataStack). This OperationQueue has a maximum number of operations set to 1. private lazy var historyQueue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 return queue }() When a Core Data notification is received, a new task is added to this serial operation queue. So if many notifications are received, they will all be performed one after the other one in a serial way. @objc func storeRemoteChange(_ notification: Notification) { // Process persistent history to merge changes from other coordinators. historyQueue.addOperation { self.processPersistentHistory() } } In this Loading and Displaying a Large Data Feed Sample Code, Apple uses Tasks to handle history changes (in QuakesProvider). // Observe Core Data remote change notifications on the queue where the changes were made. notificationToken = NotificationCenter.default.addObserver(forName: .NSPersistentStoreRemoteChange, object: nil, queue: nil) { note in Task { await self.fetchPersistentHistory() } } I feel something is wrong in the second project as Tasks could happen in any order, and not necessarily in a serial order (contrary to the first project where the OperationQueue as a maxConcurrentOperationCount = 1). Should we use an actor somewhere to make sure the methods are serially called? I thought about an implementation like this but I’m not yet really comfortable with that: actor PersistenceStoreListener { let historyTokenManager: PersistenceHistoryTokenManager = .init() private let persistentContainer: NSPersistentContainer init(persistentContainer: NSPersistentContainer) { self.persistentContainer = persistentContainer } func processRemoteStoreChange() async { print("\(#function) called on \(Date.now.formatted(date: .abbreviated, time: .standard)).") } } where the processRemoteStoreChange method would be called by when a new notification is received (AsyncSequence): notificationListenerTask = Task { let notifications = NotificationCenter.default.notifications(named: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator) for await _ in notifications { print("notificationListenerTask called on \(Date.now.formatted(date: .abbreviated, time: .standard)).") await self.storeListener?.processRemoteStoreChange() } }
Replies
1
Boosts
0
Views
5.9k
Activity
Mar ’22
Delay contextMenu on SwiftUI
I'm trying to delay when the contextMenu appears because I have a drag gesture over the same view which causes a confuse user experience. My code: … Text(exampleText) .contextMenu { delay() // Menus here } .gesture( DragGesture() .onEnded( { end in switch exampleTextAlignment { case .leading: if end.translation.width > 0 { exampleTextAlignment = .center onContextMenuAlignment = .top } case .center: if end.translation.width < 0 { exampleTextAlignment = .leading onContextMenuAlignment = .topLeading } else if end.translation.width > 0 { exampleTextAlignment = .trailing onContextMenuAlignment = .topTrailing } case .trailing: if end.translation.width < 0 { exampleTextAlignment = .center onContextMenuAlignment = .top } } } ) ) … where delay() is: … private func delay() async { try? await Task.sleep(nanoseconds: UInt64(secondsHere * Double(NSEC_PER_SEC))) hasTimeElapsed = true } … Xcode v.13.2 and iOS v.15.2. Here's a more detailed question: https://stackoverflow.com/questions/71201562/delay-contextmenu-on-swiftui
Replies
0
Boosts
0
Views
1.3k
Activity
Feb ’22
SectionedFetchRequest mixes up the sections
I am presenting a list of Items which are sections by the categoryIdentifier property. My app uses CloudKit. When I add change the categoryIdentifier for an item it is display in the correct section and other running instances of the app do the same. When restarting the app some items are grouped under an incorrect section, but the cstegoryIdentifier within the item is still as it was set. My question is what I'm doing wrong that upon restart the organization is incorrect. In case it matters, I'm setting this in the container:         container.viewContext.automaticallyMergesChangesFromParent = true As an aside: It seems necessary to make the sectioning type optional (as is the case in the underlying entity) like this SectionedFetchResults<String?, Item> Though the examples don't seem to need this. struct ContentView: View {     @Environment(\.managedObjectContext) private var viewContext     @State private var isShowingItem = false     @State private var isAddingItem = false          @SectionedFetchRequest(         sectionIdentifier: \.categoryIdentifier,         sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: true)],         animation: .default) private var sectionedItems: SectionedFetchResults<String?, Item>          var body: some View {         NavigationView {             List {                 ForEach(sectionedItems) { section in                     Section(header: Text(Category.nameForId(section.id, context: viewContext)).font(.headline)) {                         ForEach(section) { item in                             NavigationLink(destination: ItemInputView(item: item, category: Category.get(identifier: item.category, context: viewContext))) {                                 Text(item.getName())                             }                         }                     }                 }             }                          .navigationTitle("Foo")             .sheet(isPresented: $isAddingItem) {                 ItemInputView(item: nil, category: Category.getDefault(context: viewContext))             }         }         .navigationViewStyle(.stack)     } }
Replies
1
Boosts
0
Views
1.3k
Activity
Jan ’22