-2

I have a method with a completion that returns a bool. But I cant figure out how to get around this error.

Error

UISwitch.isOn must be used from main thread only

Button Action

@IBAction func notificationSwitch(_ sender: Any) {
    
    LocalNotification().checkEnabled(completion: { (success) -> Void in
        
        // When download completes,control flow goes here.
        if success == false{
            print("Cant Turn On")
            self.notificationToggle.isOn = false
        } else {
            print("Can Turn On")
            if self.notificationToggle.isOn == true {
                self.notificationToggle.isOn = false
            } else {
                self.notificationToggle.isOn = true
            }
        }
    })
}

also already tried wrapping the LocalNotifications().... in DispatchQueue.main.async but still get the same error

Asif Mujtaba
  • 447
  • 6
  • 17
  • 1
    Do you understand the word "asynchronous"? `getNotificationSettings` is asynchronous; you cannot return from `checkEnabled` any value that depends upon it. Please read http://www.programmingios.net/what-asynchronous-means/ – matt Jul 04 '20 at 21:48
  • couldnt I add a completion to this method? Ive tried that but I dont know how to call the method to retrieve the completion bool @matt – asdfohcoibewaib Jul 04 '20 at 21:54
  • You could certainly add a completion handler parameter. — Unfortunately you've now edited the question so drastically that it's no longer clear what it's about. I've tried to answer what it seems to be about _now_. – matt Jul 04 '20 at 22:43

1 Answers1

1

You're almost there. It is not the checkEnabled that needs to be wrapped in the call to get onto the main thread, but the stuff "inside" it:

    LocalNotification().checkEnabled(completion: { (success) -> Void in
        DispatchQueue.main.async {
            if success == false {
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Yes this helps with the error, but do you know why once `self.notificationToggle.isOn = true` It continues to stay on true and wont change to false if clicked on again? – asdfohcoibewaib Jul 04 '20 at 22:52
  • Actual that part was my bad but your answer is what I was looking for thanks for providing an answer unlike @Matt who thinks he is – asdfohcoibewaib Jul 04 '20 at 23:02