You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SecTrustEvaluateWithError致UI无响应,异步调用如何返回结果?

解决方案

你的问题核心在于同步函数无法直接等待异步操作完成后返回值,因为DispatchQueue.global().async是异步执行的,不会阻塞当前线程,所以原有的同步返回Bool的写法行不通。必须将函数改为异步模式,下面提供两种常用的实现方式:

1. 闭包回调方式(兼容旧版本Swift)

把函数改成接受一个闭包参数,在后台执行完SecTrustEvaluateWithError后,通过闭包返回结果(如果后续需要更新UI,记得切回主线程):

func checkIsError(someDate: Date, trust: SecTrust, completion: @escaping (Bool) -> Void) {
    DispatchQueue.global().async {
        var someError: SomeError?
        // 验证逻辑:评估成功且无错误则返回true,否则false
        let isValid = SecTrustEvaluateWithError(trust, &someError) && someError == nil
        // 切回主线程回调(适配UI操作场景)
        DispatchQueue.main.async {
            completion(isValid)
        }
    }
}

// 调用示例
checkIsError(someDate: yourDateValue, trust: yourTrustInstance) { isErrorFree in
    if !isErrorFree {
        // 对应你需要返回false的失败处理逻辑
        print("信任评估失败")
    } else {
        print("信任评估通过")
    }
}

2. Async/Await方式(Swift 5.5+,iOS 15+/macOS 12+及以上)

利用Swift并发框架,将函数改为异步函数,代码更简洁易读:

func checkIsError(someDate: Date, trust: SecTrust) async -> Bool {
    return await withCheckedContinuation { continuation in
        DispatchQueue.global().async {
            var someError: SomeError?
            let isValid = SecTrustEvaluateWithError(trust, &someError) && someError == nil
            continuation.resume(returning: isValid)
        }
    }
}

// 调用示例(需在异步上下文执行,比如Task内)
Task {
    let isErrorFree = await checkIsError(someDate: yourDateValue, trust: yourTrustInstance)
    if !isErrorFree {
        // 处理失败逻辑
    }
}

注意点

  • 原代码中的trust变量建议作为函数参数传入,避免隐式依赖全局变量,提升代码可维护性。
  • 无论哪种方式,都不要在主线程执行SecTrustEvaluateWithError,否则会导致UI卡顿,这也是你收到警告的原因。

内容的提问来源于stack exchange,提问作者Marko Markovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:45:45