UIApplication.delegate should only be used from the main thread

I have the following code in my delegate deletion as a shortcut for working with CoreData in my other view controllers:

let ad = UIApplication.shared.delegate as! AppDelegate let context = ad.persistentContainer.viewContext 

However, now I get the error message:

"UI API called from background thread" and "UIApplication.delegate should be used only from the main thread."

I am working with CoreData while my application is in the background, but this is the first time I have seen this error message. Does anyone know what is going on here?

Update: I tried moving this inside the appDelegate class itself and using the following code -

 let dispatch = DispatchQueue.main.async { let ad = UIApplication.shared.delegate as! AppDelegate let context = ad.persistentContainer.viewContext } 

Now I can no longer access declarations and context variables outside of AppDelegate . Is something missing?

+5
source share
1 answer

With reference to this ( - [UIApplication delegate] should only be called from the main thread ) in Swift (for your permission request)

  DispatchQueue.main.async(execute: { // Handle further UI related operations here.... //let ad = UIApplication.shared.delegate as! AppDelegate //let context = ad.persistentContainer.viewContext }) 

With permission: (Where is the place to declare the announcement and the context? Should I declare them in my view Controllers in the main dispatch)
Declaring a place for variables (declaration and context) defines the scope for it. You need to decide what the scope of this variable will be. You can declare them a Project or Application level (globally), a class level, or a specific level of this function. If you want to use this variable in other ViewControllers, declare it globally or at the class level using open / open / internal access control.

  var ad: AppDelegate! //or var ad: AppDelegate? var context: NSManagedObjectContext! //or var context: NSManagedObjectContext? DispatchQueue.main.async(execute: { // Handle further UI related operations here.... ad = UIApplication.shared.delegate as! AppDelegate context = ad.persistentContainer.viewContext //or //self.ad = UIApplication.shared.delegate as! AppDelegate //self.context = ad.persistentContainer.viewContext }) 
+3
source

Source: https://habr.com/ru/post/1273244/


All Articles