0

I am still struggling with this issue across many programs. I have a closure that I need a value back from but as it is with async, it's not waiting for the value and therefore the calling method is erroring because it has the wrong bool.

Here is an example:

    func requestNotificationAuthorization() -> Bool {
        var retVal: Bool = false
        let authOptions = UNAuthorizationOptions.init(arrayLiteral: .alert, .badge, .sound)
        self.userNotificationCenter.requestAuthorization(options: authOptions) { (success, error) in
            if let error = error {
                retVal = false
                print(error.localizedDescription)
            } else {
                retVal = true
            }
        }
        return retVal
    }

I need to know if the user has in fact authorized notifications but during the initial call, it will always return false or true if I set the value to an initial true. Now, it will come back with a value at some point but the code that reads it has already been processed.

There has to be a way to do this that I just haven't found yet. I am not looking for a workaround but an actual solution. Any help in pointing me in the correct direction would be greatly appreciated.

Douglas W. Palme
  • 390
  • 1
  • 4
  • 10
  • 1
    What you're trying to do is completely impossible unless you have a time machine in your pocket, because the line `return retVal` executes _before_ the line `retVal = true` — so that `retVal` must, perforce, always be `false`. Please, please, please read the three short articles starting here: http://www.programmingios.net/what-asynchronous-means/ If you can't wrap your head around this, then switch to using `async/await` which is much easier to reason about. – matt Jan 03 '23 at 01:06

0 Answers0