swift - 如何从系统函数的完成处理程序闭包中 return?

swift - how to return from a within a completion handler closure of a system function?

我知道这行不通,因为 completion handlerbackground Thread

where am I supposed do dispatch the main queue or what else do i have to do?

这是代码:

static func isNotificationNotDetermined() -> Bool{

    var isNotDetermined = false

    UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
        switch notificationSettings.authorizationStatus {
        case .notDetermined:
            isNotDetermined = true

        case .authorized:
            isNotDetermined = false

        case .denied:
            isNotDetermined = false

        }
    }

    return isNotDetermined
}

你不能那样做。这不是因为完成处理程序在后台线程上。 这是因为函数 getNotificationSettings() 是异步的。它 returns 立即,在您得到答案之前。

想象一下,你正在做晚饭,你问你的女儿"Will your brother be home for dinner?"你的女儿需要打电话给你的儿子看看。你不会一问就得到问题的答案。你得等你女儿找到一个phone,打个电话,然后给你报告。

异步函数就是这样。答案不知何时函数returns。这就是完成处理程序的用途。这是一段代码,一旦确定答案就会执行。

你不能这样做; getNotificationSettings 是异步的,所以你应该在方法中传递一个闭包并在切换之后立即调用。 像这样:

static func isNotificationNotDetermined(completion: (Bool) -> Void) {

    UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
        var isNotDetermined = false
        switch notificationSettings.authorizationStatus {
        case .notDetermined:
            isNotDetermined = true

        case .authorized:
            isNotDetermined = false

        case .denied:
            isNotDetermined = false

        }

        // call the completion and pass the result as parameter
        completion(isNotDetermined)
    }

}

然后你会这样调用这个方法:

    YourClass.isNotificationNotDetermined { isNotDetermined in
        // do your stuff
    }