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

Shell脚本存入钥匙串的数据无法通过iOS原生Swift代码读取的问题求助

Shell脚本存入钥匙串的数据无法通过iOS原生Swift代码读取的问题求助

我最近碰到一个头疼的问题:用Shell脚本把一些静态数据存入钥匙串后,尝试用iOS原生Swift代码读取这些数据,却始终拿不到结果。下面是我用到的两段代码,有没有大佬能帮我排查下问题出在哪?

用于存入数据的Shell脚本

service_name="MyKeychainService"

# Specify the account name for the keychain item
account_name="MyAccount"

# Specify the string data you want to save
string_data="YourSecretString"

# Save the string data into the keychain
security add-generic-password -a "$account_name" -s "$service_name" -w "$string_data" -U

用于读取数据的iOS Swift代码

func retrieveDataFromKeychain(service: String, account: String) -> String? {
    var query = [
        kSecClass: kSecClassGenericPassword,
        kSecAttrService: service,
        kSecAttrAccount: account,
        kSecReturnData: kCFBooleanTrue as Any,
        kSecMatchLimit: kSecMatchLimitOne
    ] as [String: Any]

    var data: AnyObject?
    let status = SecItemCopyMatching(query as CFDictionary, &data)

    if status == errSecSuccess {
        if let retrievedData = data as? Data {
            return String(data: retrievedData, encoding: .utf8)
        }
    }
    return nil
}

// 使用示例
let service = "MyKeychainService"
let account = "MyAccount"
if let retrievedData = retrieveDataFromKeychain(service: service, account: account) {
    print("Retrieved data from keychain: \(retrievedData)")
} else {
    print("Failed to retrieve data from keychain")
}

备注:内容来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 07:09:36