0

I wasn't sure if this is possible.

I would like to have a bool returned from authorizationStatus when i called UNUserNotificationCenter.current().getNotificationSettings()

I first created a callback block to determine authorizationStatus then the next function will return a bool back to the original caller.

I'm encountering non-void return value in void function as usual as my callback is returning a void.

Ideally, I would like to use checkNotificationBlocks()just like the method: isNotificationEnabled()

func checkNotificationBlocks(callback: @escaping (Bool) -> Void)
{
    UNUserNotificationCenter.current().getNotificationSettings()
        {
            settings in
            var status = false
            switch settings.authorizationStatus
            {
            case .authorized: status = true
            case .denied: status = false
            case .notDetermined: status = false
            }

            if UIApplication.shared.isRegisteredForRemoteNotifications && status == true
            {callback(true) }
            else { callback(false) }
    }

}

func isNotificationEnabledBlocks() -> Bool
{
    checkNotificationBlocks {
        b in
        if b == true { return true } //Unexpected non-void return value in void function
        else { return false } //Unexpected non-void return value in void function
    }
}
//currentUserNotificationSettings' was deprecated in iOS 10.0:
func isNotificationEnabled() -> Bool 
{
      if UIApplication.shared.isRegisteredForRemoteNotifications && settings.types.rawValue != 0
        { print("isNotificationEnabled return true"); return true }
        else { print("isNotificationEnabled return false");return false }
    }
Desmond
  • 5,001
  • 14
  • 56
  • 115
  • 3
    `getNotificationSettings` is an asynchronous method, so you cannot write a synchronous wrapper like `isNotificationEnabledBlocks` (well you can, with GDC magic and stuff, by blocking the current thread until the result is here.. but I don't think that's what you want). Instead you need to handle the asynchronism in your code and use your `checkNotificationBlocks` helper directly. – dr_barto Jul 16 '18 at 08:52
  • 1
    Do you mind blocking the calling thread when doing `isNotificationEnabledBlocks()` – Ladislav Jul 16 '18 at 11:11
  • @Ladislav i don mind blocking the thread – Desmond Jul 16 '18 at 18:09

1 Answers1

2

I eventually did updated my code to get my desired outcome. The semaphore obtains a lock when it makes wait call and it's released when it's signaled from the asynchronous block.

 func isNotificationEnabledBlocks() -> Bool
{
    let waitOut = DispatchSemaphore(value: 0)
    var checks = false

    checkNotificationBlocks {
        b in checks = b
        waitOut.signal()
    }
    waitOut.wait()
    return UIApplication.shared.isRegisteredForRemoteNotifications && checks == true ? true : false
}
Desmond
  • 5,001
  • 14
  • 56
  • 115