NSUserDefault不存储值

时间:2016-03-29 06:40:11

标签: ios swift nsuserdefaults

您好我在用户成功登录时保存了值。

case 200:
           let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
                        prefs.setObject(email, forKey: "EMAIL")
                        prefs.setObject(result["User"]!["profile_image"], forKey: "PROFILEIMAGE")
                        prefs.setObject(result["User"]!["first_name"], forKey: "FIRSTNAME")
                        prefs.setObject(result["User"]!["last_name"], forKey: "LASTNAME")
                        prefs.setObject(result["User"]!["Country"], forKey: "COUNTRY")
                        prefs.setObject(result["User"]!["user_id"], forKey: "USERID")

                        prefs.setObject(result["User"]!["session_token"], forKey: "SESSIONTOKEN")
                        prefs.setInteger(1, forKey: "ISLOGGEDIN")

                        prefs.synchronize()


                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            let nav : SWRevealViewController = self.storyboard!.instantiateViewControllerWithIdentifier("swrevealviewcontroller") as! SWRevealViewController
                            self.navigationController?.presentViewController(nav, animated: true, completion: { () -> Void in
                            })                            
                        })


                        break;

当我尝试获取此值

时,我的PROFILEIMAGE值为nil
let userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
        print("userdefault is \(userDefaults.stringForKey("PROFILEIMAGE"))")

所以为了检查手机中存储的所有键和值,我做了这个

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation())

我检查了控制台,但我在控制台中找不到COUNTRYPROFILEIMAGE键和值

请帮助我,我在这里做错了什么

1 个答案:

答案 0 :(得分:0)

检查数据(字符串值)是否为零。

if let url: String = result["User"]!["profile_image"] {
    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    prefs.setObject(result["User"]!["profile_image"], forKey: "PROFILEIMAGE")
   prefs.synchronize()
}

并且反过来:

let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
if let storedURL: String = prefs.objectForKey(PROFILEIMAGE) as? String{
// Do your stuff

}