简体   繁体   中英

Error "Trailing closure passed to parameter of type 'NSManagedObjectContext' that does not accept a closure" in Swift

I try to add a live activity to my app, in Swift. But when I try to run the app, the error message "Trailing closure passed to parameter of type 'NSManagedObjectContext' that does not accept a closure" appear. My app uses Core Data to save the data of my app.

class HabitManager: ObservableObject {
    private var activity: Activity<HabitsWidgetAttributes>? = nil

    func startHabit(name: String, symbol: String, currentTask: String) {
        let attributes = HabitsWidgetAttributes(name: name, symbol: symbol)
        let state = HabitsWidgetAttributes.ContentState(currentTask: currentTask)
    
        activity = try? Activity<HabitsWidgetAttributes>.request(attributes: attributes, contentState: state)
    }

    func updateActivity(nextTask: String) {
        let state = HabitsWidgetAttributes.ContentState(currentTask: nextTask)
    
        Task { // Line where the error is generated
            await activity?.update(using: state)
        }
    }

    func stopActivity() {
        let state = HabitsWidgetAttributes.ContentState(currentTask: "Finished")
    
        Task { // Line where the error is generated
            await activity?.end(using: state, dismissalPolicy: .immediate)
        }
    }
}

If you create a CoreData entity called Task, then the compiler will try to use that instead of the Swift Task struct.

You can either rename your CoreData entity to something else (which I'd recommend), or you can call an async task by prefixing it with the module, in this case it would look like this:

Swift.Task {
  // do stuff
}

Since you'd have to do that everywhere, I would strongly recommend renaming your entity instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM