【问题标题】:authorizationStatus return a bool value授权状态返回一个布尔值
【发布时间】:2018-07-16 08:43:40
【问题描述】:

我不确定这是否可行。

当我调用UNUserNotificationCenter.current().getNotificationSettings() 时,我希望从authorizationStatus 返回一个布尔值

我首先创建了一个回调块来确定authorizationStatus,然后下一个函数将返回一个布尔值给原来的调用者。

我像往常一样在 void 函数中遇到非 void 返回值,因为我的回调返回一个 void。

理想情况下,我想使用checkNotificationBlocks()就像方法: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 }
    }

【问题讨论】:

  • getNotificationSettings 是一种异步方法,因此您不能编写像isNotificationEnabledBlocks 这样的同步包装器(您可以使用 GDC 魔法和其他东西,通过阻塞当前线程直到结果出现在这里..但我认为这不是你想要的)。相反,您需要处理代码中的异步并直接使用您的 checkNotificationBlocks 助手。
  • 在做isNotificationEnabledBlocks()时介意阻塞调用线程
  • @Ladislav 我不介意阻塞线程

标签: ios swift callback unusernotificationcenter


【解决方案1】:

我最终确实更新了我的代码以获得我想要的结果。 信号量在进行等待调用时获得锁,并在异步块发出信号时释放。

 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
}

【讨论】:

    猜你喜欢
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 2013-08-18
    相关资源
    最近更新 更多