This question already has an answer here:
Expected Declaration Error using Swift
(1 answer)
Closed 6 years ago.
I'm writing code for a game I am making and am trying to create a User Default so that it saves data after you close the app.
let UserDefaults = NSUserDefaults.standardUserDefaults()
UserDefaults.setBool(false, forKey: "hasStarted")
But on the last line it underlines UserDefaults and says "expected declaration.
What have I done wrong?
In you are using Swift 2, then what you have to do is just putting your code inside a function/method:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(false, forKey: "hasStarted")
like so, in:
func applicationWillTerminate( application: UIApplication) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(false, forKey: "hasStarted")
}
or here:
func applicationWillResignActive( application: UIApplication) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(false, forKey: "hasStarted")
}
I've called it there because you said that you want it to save it when the app is closed.
EXPLANATION:
You called your function outside any function/method's body, which is restricted in swift. You are not allowed to do anything outside methods(just in the body of the class), besides for declaring and initialising variables/constants.
Where are you declaring and intializing the variable? If you are initializing the variable outside any method then it will give you the same error you mentioned
Try another name for it.
Try this:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(false, forKey: "hasStarted")
Related
This question already has answers here:
Attempt to insert non-property list object when trying to save a custom object in Swift 3
(6 answers)
Save custom objects into NSUserDefaults [duplicate]
(2 answers)
Closed 3 years ago.
I am not able to save the list of viewControllers in my user defaults, its getting crashed at this userDefault.set(vcList, forKey: "vcList").
The error log says:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object
import UIKit
class ViewController: UIViewController {
struct viewControllerList {
var vc1 = ViewController()
var vc2 = LoginViewController()
}
override func viewDidLoad() {
super.viewDidLoad()
let vcList = viewControllerList()
let userDefault = UserDefaults.standard
userDefault.set(vcList, forKey: "vcList")
}
}
Please help!
The UserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.
A default object must be a property list—that is, an instance of (or for collections, a combination of instances of) NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.
You can try this
//MARK:- Save viewController in UserDefault
func saveInDefaults(_ viewController : UIViewController) -> Void{
do {
let encodeData = try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false)
UserDefaults.standard.set(encodeData, forKey: "vcList")
UserDefaults.standard.synchronize()
} catch {
print("error")
}
}
And Call function from viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
let vcList = viewControllerList()
self.saveInDefaults(vcList)
}
In my application, I use UserDefaults to store the user's login status (whether they are logged in or not), and their username. It works fine in that when I login, close the app, and open it again my app skips the login page and recognizes that I am already logged in. Although, I am now trying to install a logout button to a separate viewController. When clicked, this logout button needs to 1.) Reset UserDefaults.loginStatus to "False" 2.) Reset UserDefaults.username to nil 3.) Perform a segue to the login page.
Here is the related code from my ViewController.swift file. This is the first viewController which controls the loginPage.
import UIKit
import Firebase
let defaults = UserDefaults.standard
class ViewController: UIViewController {
func DoLogin(username: String, password: String) {
//I Am not including a lot of the other stuff that takes place in this function, only the part that involves the defaults global variable
defaults.setValue(username, forKey: "username")
defaults.setValue("true", forKey: "loginStatus")
defaults.synchronize()
self.performSegue(withIdentifier: "loginToMain", sender: self) //This takes them to the main page of the app
}
override func viewDidLoad() {
super.viewDidLoad()
if let stringOne = defaults.string(forKey: "loginStatus") {
if stringOne == "true" { //If the user is logged in, proceed to main screen
DispatchQueue.main.async
{
self.performSegue(withIdentifier: "loginToMain", sender: self)
}
}
}
}
Below is my code in SecondViewController.swift, particularly the logout function.
import UIKit
import Firebase
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let username = defaults.string(forKey: "username") {
checkAppSetup(username: username) //This is an unrelated function
//I included this because this works fine. Proving that I am able to read the defaults variable fine from this other viewController
}
}
#IBAction func logout(_ sender: Any) {
defaults.setValue("false", forKey: "username")
defaults.setValue("false", forKey: "loginStatus")
defaults.synchronize()
performSegue(withIdentifier: "logoutSegue", sender: nil)
}
When the logout function is run, the segue performs fine but the default values do not change. Can someone explain why and what I can do to get around this?
**Side note, I am not actually going to set the defaults to "false" and "false". That is just temporary for while I am debugging this issue.
Several things.
You should be using set(_:forKey:) and object(_:forKey) to read and write key/value pairs to defaults, not setValue(_:forKey). (Your use of defaults.string(forKey: "loginStatus") is correct, however.)
You should probably be writing a nil to the userName key:
defaults.set(nil, forKey: "username")
And your logout IBAction should almost certainly be setting loginStatus to false, not true.
Try changing those things.
Also, there is no reason to call synchronize unless you are terminating your app in Xcode rather than pressing the home button on the device/simulator in order to let it exit normally.
Hey i used the exactly same concept recently :
1) In your initial view, in the viewDidLoad() , check whether somebody is already logged in or not, and only one user can be logged in one device at a time, so we check like
let defaults = UserDefaults.standard
if defaults.object(forKey: "userName") != nil && defaults.object(forKey: "userPassword") != nil
{
let loginObject = self.storyboard?.instantiateViewController(withIdentifier: "YourSecondViewController") as! YourSecondViewController
//As someone's details are already saved so we auto-login and move to second view
}}
2) In your sign in button function , check whatever condition you want to check and then, inside the same, if condition satisfies then save data to userDefaults.
// If no details are saved in defaults, then control will come to this part, where we will save the entered userName and Password
let defaults = UserDefaults.standard
defaults.set(self.enteredUseName, forKey: "userName")
defaults.set(self.enteredPassword, forKey: "Password")
defaults.synchronize()
3) On logout button , delete the userDefaults and load the login view again :
let defaults = UserDefaults.standard
defaults.removeObject(forKey: "userName") //We Will delete the userDefaults
defaults.removeObject(forKey: "userPassword")
defaults.synchronize() //Sync. the defaults.
navigationController?.popToRootViewController(animated: true) //Move Back to initial view.
4) If you are using a navigation control, that you must be using :P then you will surely see the back button which will open the second view if clicked, for that you can hide the navigation bar in viewDidLoad() of your login view
self.navigationController?.navigationBar.isHidden = true
My textfield is not saving. My code is listed below. Thanks
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var textext: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func savesavesave(_ sender: Any) {
let myText = textext.text
UserDefaults.standard.set(myText, forKey: "myKey")
}
Ensure your textfield is not being first responder. For example, you may call the below code before saving:
#IBAction func savesavesave(_ sender: Any) {
textext.resignFirstResponder()
let myText = textext.text
UserDefaults.standard.set(myText, forKey: "myKey")
}
You should try this for saving textfield into UserDefaults:
let myText = TextFiled1.text
UserDefaults.standard.set(myText, forKey: "myKey")
If you want to get that textfield value then write this:
let value = UserDefaults.standard.string(forKey: "myKey")
print(value!)
Synchronize the user defaults with its method and test if working
I'm writing from my memory:
UserDefaults.standard.set(myText, forKey: "myKey")
UserDefaults.standard.synchronize()
EDIT
from apple documentation
// Note that we don't synchronize with the file system or anything; this will happen
when the app quits. There are times when an explicit synchronize might be necessary,
but often it's not. Synchronizing unecessarily can also be a performance issue.
According apple docs I understands (you may think otherwise) that if you want to get the value during runtime, and not saving it in your variable - you should sync manually
EDIT AGAIN
Thanks to #LeoDabus I understand that maybe it's available during runtime too. So don't count my answer
Yes, it is not necessary synchronize happens, if app is about to exit. For accessing the information during app launches it is necessary that the synchronization happens. For more info you can check: iOS NSUserDefaults access before synchronize completion
How to pass the state of a NSUserDefault between several Classes in Swift?
In this case I want to pass this state between one TableViewController, where you change the state on the switch, and one initial VC.
Here is a little model to understand...
I used this to set the state with the switch:
#IBAction func changeTouchIDState(sender: AnyObject) {
if TouchIDSwitch.on {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "State")
} else {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "State")
}
}
If the state = true, the initial VC should ask about the Authentication.
Thanks!
Your question need little more explanation, I don't understand why you want to pass the value as you are already storing in NSUserDefaults which you can access in any class of your app.
As per my understanding to your problem I'm suggesting the solution:
As you already storing State in NSUserDefaults so before presenting initial VC check NSUserDefaults.standardUserDefaults().boolForKey("State") if its true, ask authentication otherwise don't.
After setting the bool, you should synchronise:
NSUserDefaults.standardUserDefaults().synchronize()
Then, you can access that value with:
func boolForKey(_ defaultName: String) -> Bool
I'm trying to use a language change button, I'm using the following:
NSUserDefaults.standardUserDefaults().setObject(["de"], forKey:
"AppleLanguages") NSUserDefaults.standardUserDefaults().synchronize()
But it only works when the application is restarted.
How I can change the language at runtime?
IN SWIFT 3
1. Download "NSBundle+Language" .h .m classes from here
https://gist.github.com/narikbi/352e93e446e8b1faf283
2. #import "NSBundle+Language.h" in to Objective-c bridging Header file for swift use
3. Put this global method in to your "Appdelegate.swift":-
//MARK:- Language Setter
public func changeLanguage(){
if var arr = (UserDefaults.standard.object(forKey: "AppleLanguages") as? [String]){
let changedKey = arr[0] == "ja" ? "en":"ja"
//this will set current language key for future use
UserDefaults.standard.set([changedKey], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
//Run time conversion if you want
Bundle.setLanguage(changedKey)//Magic Line ;)
}
}
4. Use any where in your controller with UIButton or Switch toggle Action :-
#IBAction func btnSwitchTaped(_ sender: Any) {
print(UserDefaults.standard.object(forKey: "AppleLanguages") ?? "")
(UIApplication.shared.delegate as! AppDelegate).changeLanguage()
//if you want to check your string programatically on console print when switch toggle value(testing purpose)
let check = NSLocalizedString("Test", comment: "testing")
print(check)
}
Happy coding :)