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

Swift跨平台(macOS+iOS)Firebase Auth持久化异常求助

解决iOS/macOS单目标应用Firebase Auth认证状态持久化冲突问题

核心问题原因

iOS和macOS对应用组/钥匙串访问组的格式要求存在差异:

  • iOS要求应用组必须以group.开头,Firebase Auth的用户访问组无需附加Team ID($(AppIdentifierPrefix)会自动填充)
  • macOS需要钥匙串访问组带Team ID前缀才能正常读写钥匙链,否则会触发FIRAuthErrorDomain Code=17995错误

分步解决方案

1. 配置平台专属的Entitlements

打开项目的Entitlements.plist,针对iOS和macOS分别设置正确的权限组:

  • iOS平台:
    • 应用组:group.com.teamName.appName
    • 钥匙串共享组:$(AppIdentifierPrefix)com.teamName.appName
  • macOS平台:
    • 应用组:$(AppIdentifierPrefix)group.com.teamName.appName
    • 钥匙串共享组:$(AppIdentifierPrefix)com.teamName.appName

在Xcode中实现平台区分的最简单方式:

  1. 选中Entitlements.plist,右键选择Open As -> Source Code
  2. 替换为以下带条件分支的代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.application-groups</key>
    <array>
        <!-- iOS 平台配置 -->
        <string condition="TARGET_OS_IPHONE">group.com.teamName.appName</string>
        <!-- macOS 平台配置 -->
        <string condition="TARGET_OS_MAC">$(AppIdentifierPrefix)group.com.teamName.appName</string>
    </array>
    <key>keychain-access-groups</key>
    <array>
        <string>$(AppIdentifierPrefix)com.teamName.appName</string>
    </array>
</dict>
</plist>

2. 条件化初始化Firebase Auth访问组

在App启动的初始化代码中,根据运行平台传入对应的访问组:

import FirebaseAuth

func configureFirebaseAuth() {
    guard let appIdentifierPrefix = Bundle.main.infoDictionary?["AppIdentifierPrefix"] as? String else {
        fatalError("无法获取Team ID前缀,请检查项目配置")
    }
    
    let userAccessGroup: String
    #if os(iOS)
    userAccessGroup = "group.com.teamName.appName"
    #elseif os(macOS)
    userAccessGroup = appIdentifierPrefix + "group.com.teamName.appName"
    #endif
    
    do {
        try Auth.auth().useUserAccessGroup(userAccessGroup)
    } catch {
        print("Firebase Auth 访问组配置失败: \(error.localizedDescription)")
    }
}

// 在App启动时调用
configureFirebaseAuth()

3. 同步应用扩展的配置

确保所有关联的应用扩展(通知、分享等)的Entitlements配置和主应用对应平台的配置完全一致,否则扩展将无法共享认证状态。

内容的提问来源于stack exchange,提问作者Tudor Andreescu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:51:23