tha*_*guy 5 objective-c keychain ios swift
我有一个以 HTTP cookie 形式从 Web 服务接收的身份验证令牌。目前,我依赖于 iOS 的默认行为,即将从 HTTP 请求返回的 cookie 存储在NSHTTPCookieStorage对象中,该对象会保留 cookie,直到用户关闭应用程序。
但是,我想在钥匙串中保留应用程序生命周期之间的 cookie,以便当用户重新打开应用程序时,如果他们的 cookie 没有过期,他们将不需要再次登录。似乎没有一种简单的方法可以将通用对象存储到钥匙串中,因此最好的方法似乎是将通过NSHTTPCookie's检索到的字典对象序列化为property字符串并将其存储在钥匙串中。然后我可以通过initWithProperties构造函数重建cookieNSHTTPCookie并将其粘贴回NSHTTPCookieStorage对象中。
在 Swift 中执行此操作的最简单方法是什么?我发现 Apple 编写的代码称为“KeychainItemWrapper”,但它的文档相当参差不齐,似乎它是用于存储用户的电子邮件(或用户名)和密码,而不是通用对象。有没有更简单的方法来使用钥匙串,或者有更好的方法来安全地存储 Web 服务的身份验证令牌?
您应该查看 SSKeychain: https: //github.com/soffes/sskeychain。它在钥匙串 API 上有一个非常漂亮且可用的界面。
它本身不是 Swift,但您仍然应该能够在 Swift 应用程序中使用它。我认为没有办法存储对象本身,但正如您提到的,您可以将 cookie 序列化为字符串并将其保存在钥匙串中。
下面的示例说明了如何使用它。
NSString * const LoginService = @"com.example.loginService"; // unique identifier shared across your apps to identify various services your app may provide that require the keychain
NSString *cookie = // cookie string
NSString *userAccountIdentifier = // could be an email, username, id, or some other way to uniquely identify the user
[SSKeychain setPassword:cookie forService:LoginService account:userAccountIdentifier error:&error];
Run Code Online (Sandbox Code Playgroud)