Search code examples
iosswiftuilocalnotificationlocalnotification

Swift Local Notifications Checker Main Thread Only


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


Solution

  • 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 {