Storing a Boolean for access by Parse login

112 Views Asked by At

I want to store a Boolean which grants access to certain options when a user logs in with Parse, but when I log in and declare it to be true, the variable seems to remain false.

I tried using NSUserDefaults and storing a global variable.

This is where I log in on one view controller:

 PFUser.logInWithUsernameInBackground(userName.text!, password: password.text!) {
            (user: PFUser?, error: NSError?) -> Void in

            if user != nil {


               NSUserDefaults.standardUserDefaults().setBool(true, forKey: "accessGranted")



            } 

This functions fine and prints "Success" if I try. On another view controller I have things like this:

addButton.enabled = NSUserDefaults.standardUserDefaults().boolForKey("accessGranted")
2

There are 2 best solutions below

5
Jiri Trecak On BEST ANSWER

NSUserDefaults:

Your are missing key component for it to work - you have to save the settings:

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "accessGranted")
NSUserDefaults.standardUserDefaults().synchronize()

After that, your data that you stored will be stored to disk and you can access them anytime.

One-time assign to property:

After reading through comment, in order to access property only once, you can use something like this:

var accessGranted : Bool?
if accessGranted == nil {
    accessGranted = yourValue
} 

or as of Swift 2.0 (more on it here):

var accessGranted : Bool?
guard let granted = accessGranted else {
    accessGranted = yourValue
}

Edit 2:

To notify second VC about changes, you can use multiple mechanisms (protocols / delegates etc.), but usually for this kind of message you would use Notifications (so your whole application can listen to that).

Notifications

You can use notifications like this:

In your "login" call, notify application that your access status changed, like this:

let NOTIFICATION_ACCESS_CHANGED_KEY = "NotificationAccessChanged"
NSNotificationCenter.defaultCenter().postNotificationName(NOTIFICATION_ACCESS_CHANGED)

then, everywhere where you are interested to listen to that change, put notification listener:

NSNotificationCenter.defaultCenter().addObserverForName(NOTIFICATION_ACCESS_CHANGED, object: nil, queue: nil) { (notification) -> Void in

    // This block will be called when you post notification
    self.doSomething()
}

Hope it helps!

11
Dharmesh Kheni On

You can use NSUserDefaults to store your Bool globally this way:

Set your Bool this way:

NSUserDefaults.standardUserDefaults().setBool(false, forKey: "YourKey")

Then you can access it anywhere in your project this way:

let yourBool = NSUserDefaults.standardUserDefaults().boolForKey("YourKey")

Hope this will help.