ViewControllers的条件加载停留在初始ViewController上

时间:2016-05-16 03:11:01

标签: ios swift2 nsuserdefaults

我正在尝试使用NSUserDefaults保存用户的会话,如果用户已登录,我会将NSUserDefaults设置为true,反之亦然。但是,即使输入了正确的凭据,我的用户也会永久停留在登录页面上。我该如何解决?

LoginViewController代码

import tensorflow as tf
import numpy as np


# Teach how to multiply
def generate_data(how_many):
    data = np.random.rand(how_many, 2)
    answers = data[:, 0] * data[:, 1]
    return data, answers


sess = tf.InteractiveSession()

input_data = tf.placeholder(tf.float32, shape=[None, 2])
correct_answers = tf.placeholder(tf.float32, shape=[None])

weights_1 = tf.Variable(tf.truncated_normal([2, 1], stddev=.1))
bias_1 = tf.Variable(.0)

output_layer = tf.matmul(input_data, weights_1) + bias_1

mean_squared = tf.reduce_mean(tf.square(correct_answers - tf.squeeze(output_layer)))
optimizer = tf.train.GradientDescentOptimizer(.1).minimize(mean_squared)

sess.run(tf.initialize_all_variables())

for i in range(1000):
    x, y = generate_data(100)
    sess.run(optimizer, feed_dict={input_data: x, correct_answers: y})

error = tf.reduce_sum(tf.abs(tf.squeeze(output_layer) - correct_answers))

x, y = generate_data(100)
print("Total Error: ", error.eval(feed_dict={input_data: x, correct_answers: y}))

这是我在LoginViewController中调用 handlingAuthentication 方法的地方

func handlingAuthentication(notification: NSNotification) {

    let dict = notification.object as! NSDictionary
    let errorFound = dict["error"]
    let errorMessage = dict["message"]
    print(errorFound)

    if(errorFound){
         //initialize Alert Controller
        let alertController = UIAlertController(title: "Authentication error", message: errorMessage?.string, preferredStyle: .Alert)

        //Initialize Actions
        let okAction = UIAlertAction(title: "Ok", style: .Default){
                (action) -> Void in
                self.dismissViewControllerAnimated(true, completion: nil)
            }

        //Add Actions
        alertController.addAction(okAction)

        //Present Alert Controller
        self.presentViewController(alertController, animated: true, completion: nil)

    }
    else
    {
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")

        NSUserDefaults.standardUserDefaults().synchronize()

        self.dismissViewControllerAnimated(true, completion:nil)

    }

}

HomeViewController代码

@IBAction func loginBtn(sender: AnyObject) {
let loginobj = Login(userName : self.usernameField.text!, passWord : self.pwdField.text!)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.handlingAuthentication(_:)), name:"errorPresent", object: nil)
loginobj.getRequest()
}

1 个答案:

答案 0 :(得分:0)

您使用的是不同的密钥:

因为您存储了密钥“isUserLoggedIn”

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

isUserLoggedIn将始终为false,因为您获得了另一个键“IsUserLoggedIn”

let isUserLoggedIn = NSUserDefaults.standardUserDefaults().boolForKey("IsUserLoggedIn")