iOS:如何在应用程序中存储用户名/密码? [英] iOS: How to store username/password within an app?

查看:126
本文介绍了iOS:如何在应用程序中存储用户名/密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iOS应用中有一个登录屏幕。
用户名和密码将保存在 NSUserDefaults 中,并在您再次输入应用程序时再次加载到登录屏幕中(当然, NSUserDefaults 是永久性的。

I have a login-screen in my iOS app. The username and password will be saved in the NSUserDefaults and be loaded into the login-screen again when you enter the app again (of course, NSUserDefaults are permanent).

现在,用户可以禁用用户名/密码保存功能。

Now, the user have the possibility to disable the username/password saving feature.

所以 NSUserDefaults 将被清除。

但在我的应用程序中我需要这个用户名/密码用于用户的数据库查询。
所以:除了 NSUserDefaults 之外,哪里可以存储数据?
(当用户退出应用程序或退出时,可以/应该删除此地点。)

But In my app I need this username/password for database queries for the user. So: Where to store the data except NSUserDefaults? (This place can / should be deleted when the user quit the app or logout).

推荐答案

你应该总是使用钥匙串存储用户名和密码,并且由于它是安全存储的,只有您的应用可以访问,因此无需在应用退出时将其删除(如果您担心这一点)。

You should always use Keychain to store usernames and passwords, and since it's stored securely and only accessible to your app, there is no need to delete it when app quits (if that was your concern).

Apple提供示例代码,用于存储,读取和删除钥匙串项目,以及如何使用该示例中的钥匙串包装类,这大大简化了使用钥匙串。

Apple provides sample code that stores, reads and deletes keychain items and here is how to use the keychain wrapper class from that sample which greatly simplifies using Keychain.

包括Security.framework (在Xcode 3中右键单击frameworks文件夹并添加现有框架。在Xcode 4中选择你的项目,然后选择目标,转到Build Phases选项卡,然后点击链接二进制文件下的+)和KeychainItemWrapper .h& .m文件到你的项目中,#import .h文件,无论你需要使用keychain,然后创建这个类的实例:

Include Security.framework (in Xcode 3 right-click on frameworks folder and add existing framework. In Xcode 4 select your project, then select target, go to Build Phases tab and click + under Link Binary With Files) and KeychainItemWrapper .h & .m files into your project, #import the .h file wherever you need to use keychain and then create an instance of this class:

KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];

YourAppLogin 可以是您选择调用钥匙串项目的任何内容如果需要可以有多个项目)

(YourAppLogin can be anything you chose to call your Keychain item and you can have multiple items if required)

然后你可以使用以下方式设置用户名和密码:

Then you can set the username and password using:

[keychainItem setObject:@"password you are saving" forKey:kSecValueData];
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];

让他们使用:

NSString *password = [keychainItem objectForKey:kSecValueData];
NSString *username = [keychainItem objectForKey:kSecAttrAccount];

或者使用以下方式删除它们:

Or delete them using:

[keychainItem resetKeychainItem];

这篇关于iOS:如何在应用程序中存储用户名/密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆