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

Swift/SwiftUI请求日历权限时页面异常跳转问题求助

问题分析与解决方案

你的核心问题在于:当前代码中await getAccess()并没有真正等待用户处理完权限弹窗,因为requestAccess(to:completion:)是基于闭包的异步API,async关键字在这里只是空壳,导致后续的权限判断逻辑在弹窗还未处理时就提前执行,引发页面错误跳转。

修正后的代码实现

1. 重构权限请求函数(转为真正的Async/Await形式)

将闭包式的权限请求包装成async/await兼容的函数,确保await能等待用户操作完成:

func getAccess() async throws -> Bool {
    return try await withCheckedThrowingContinuation { continuation in
        eventStore.requestAccess(to: .event) { granted, error in
            if let error = error {
                continuation.resume(throwing: error)
            } else {
                continuation.resume(returning: granted)
            }
        }
    }
}

2. 修改按钮点击逻辑

直接基于权限请求的返回结果处理页面跳转,避免提前读取状态:

Task {
    do {
        let granted = try await getAccess()
        withAnimation {
            // 根据权限结果跳转对应页面
            step = granted ? step + 2 : step + 1
        }
    } catch {
        // 处理权限请求中的异常(如系统错误、用户中断)
        withAnimation {
            step = step + 1 // 跳转到错误处理页面
        }
    }
}

关键说明

  • withCheckedThrowingContinuation将闭包回调的异步操作转换为async/await范式,确保代码会等待用户完成权限弹窗操作后再执行后续逻辑。
  • 直接使用权限请求返回的granted值,比调用EKEventStore.authorizationStatus更及时准确,避免状态同步延迟问题。
  • 新增错误处理分支,覆盖权限请求过程中可能出现的异常场景。

内容的提问来源于stack exchange,提问作者Tanner George

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:52:09