ios Swift:如何存储用户偏好?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30041765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: How to store user preferences?
提问by Nick
I am still very new to iOS development and swift and am not sure if I'm overthinking this. I am currently working on an application that upon opening requires the user to enter their login credentials. This gets tedious and frustrating because every time the app is closed and opened again the user has to sign in. Is there a simple way to make the program remember if a user is already signed in?
我对 iOS 开发和 swift 仍然很陌生,我不确定我是否想得太多了。我目前正在开发一个应用程序,该应用程序在打开时要求用户输入其登录凭据。这变得乏味和令人沮丧,因为每次关闭并再次打开应用程序时,用户都必须登录。是否有一种简单的方法可以让程序记住用户是否已经登录?
I was looking into CoreData but every example involves storing a new object every time and requires a query of some sort to fetch the information. Where as all I really need is a bool isLoggedIn and an int for the stored user ID.
我正在研究 CoreData,但每个示例都涉及每次存储一个新对象,并且需要某种查询来获取信息。我真正需要的只是一个 bool isLoggedIn 和一个用于存储用户 ID 的 int。
Edit:
编辑:
NSUserDefaultsis exactly what I was looking for.
NSUserDefaults正是我想要的。
回答by Ben Lu
You can use NSUserDefaults
to save information and retrieve it next time when the app launches.
您可以使用NSUserDefaults
保存信息并在应用程序下次启动时检索它。
For example:
例如:
NSUserDefaults.standardUserDefaults().setObject("mynameisben", forKey: "username")
let userName = NSUserDefaults.standardUserDefaults().stringForKey("username")
Update for Swift 3+
Swift 3+ 的更新
UserDefaults.standard.set("mynameisben", forKey: "username")
let userName = UserDefaults.standard.string(forKey: "username")
回答by Exceptions
Use NSUserDefaults
用 NSUserDefaults
Let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("User", forKey: "userName")
Check if User name exists when application is started in your AppDelegate.swift
在您的应用程序启动时检查用户名是否存在 AppDelegate.swift
didFinishLaunchingWithOptions
If username exists, skip login page
如果用户名存在,跳过登录页面
To check if NSUserDefaults is nil
检查是否 NSUserDefaults is nil
if (defaults.objectForKey(userName) != nil) {
// Skip Login
}
else {// Show login
}