32

When I using Swift4in Xcode 9 gives me

UIApplication.delegate must be used from main thread only

.... must be used from main thread only

UI API called from background thread Group

Purple Warning.

My codes;

var appDelegate = UIApplication.shared.delegate as! AppDelegate
public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let prefs:UserDefaults = UserDefaults.standard
var deviceUUID = UIDevice.current.identifierForVendor!.uuidString

Warning line is;

  public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

Another warning like this;

 let parameters = [
                        "tel": "\(self.phone.text!)"
                        ] as [String : String]

Gives

UITextField.text must be used from main thread only

Same error again..

How can I fix it ? Any idea ?

1 Answer 1

70

You're making this call on a background queue. To fix, try something like…

public var context: NSManagedObjectContext

DispatchQueue.main.async {

    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    context = appDelegate.persistentContainer.viewContext        
}

Although this is a pretty bad way to do this… you're using your App Delegate as a global variable (which we all know is bad!)

You should look at passing the managed object context from view controller to view controller…

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 

    (window?.rootViewController as? MyViewController)?.moc = persistentContainer.viewContext
}

and so on

4
  • gives Attribute 'public' can only be used in a non-local scope error Sep 14, 2017 at 11:56
  • Did you try removing public? Sep 14, 2017 at 11:57
  • Gives many error in app, that codes in my settings.swift file this file not class, I need to move that codes in app delegate ? Sep 14, 2017 at 11:59
  • when I use that codes gives me ; Expressions are not allowed at the top level Sep 14, 2017 at 12:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.