iOS 在整个应用程序中存储 'access_token'

标签 ios objective-c

我正在尝试确定存储和访问使用 iOS 应用程序的访问 token 的最佳方式。
我正在熟悉核心数据,虽然这已证明对应用程序数据的某些部分有益,但我不确定核心数据是否最适合我需要的 token 。

大多数 View 依赖于对我们 API 的一些简单的网络请求。访问 token 与这些请求一起用于对请求的数据内容进行身份验证和授权。

为了更好地解释这里,如何使用它的示例在 AppDelegate.m 中。 .在 applicaion:hasFinishedLoadingWithOptions我使用 API 进行简单检查以确认 token ,成功时 View 更改为“主菜单”,失败时 View 更改为登录 View 。

这个 token 需要在大多数 View 中访问,因为在任何时候 API 都会使 token 失效,用户必须重新登录才能获得新 token (不是定期)。

我最初的想法是实现 token.h我可以在需要的地方调用 ViewControllers,但是由于这是我的第一个大型 iOS 应用程序,我会感觉更好一些 build 性的批评,提示或提示如何最好地访问这个 token ,“全局”,就好像它是一个静态值

最佳答案

您可以像这样将其存储在钥匙串(keychain)中
Apple 编写了一个 Objective-C 包装器,您可以使用它来简化钥匙串(keychain)的使用,包装器中的文件是 KeychainItemWrapper.h 和 KeychainItemWrapper.m,它们都包含在附加的 Xcode 项目中。

UITextField *accesstoken = [[UITextField alloc] initWithFrame:CGRectMake(40, 30, 240, 30)];
[accesstoken setBorderStyle:UITextBorderStyleRoundedRect];

KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"TestAppLoginData" accessGroup:nil];

写入钥匙串(keychain)-

//将 AcessToken 存储到钥匙串(keychain)
Nsstring *strAcessToken=@"abcd" 
[keychain setObject:strAcessToken forKey:(id)kSecAttrAccount];

从钥匙串(keychain)中读取-

//从钥匙串(keychain)中获取 AcessToken(如果存在)
[accesstoken setText:[keychain objectForKey:(id)kSecAttrAccount]];

笔记:
Writing and retrieving values from the keychain doesn’t seem to work in the simulator.
Uninstalling an application will not remove the items from the keychain. If you run the demo application on your device, and uninstall the app, the username and password will remain in the keychain (a firmware reset will, of course, remove the keychain values). 

关于iOS 在整个应用程序中存储 'access_token',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27059913/

相关文章:

ios - self.tabBarController 有时为零

ios - 获取 YouTube 视频 URL - 数据 API 3.0

ios - 如何填充 Quartz 2D 路径下方的区域?

android - 易于理解的复杂颜色选择器

ios - iOS 上的自动缩放

objective-c - MBProgressHUD 阻止用户交互

ios - iOS 应用程序中 Objective-C 代码的内存泄漏

ios - 访问 AppDelegate 属性

ios - 在 TableView Controller 中显示 nil 的原型(prototype)单元标签

objective-c - 在 Mac 应用程序窗口中设置 Tab 键顺序