Check if UserDefault exists - Swift

IosSwiftNsuserdefaults

Ios Problem Overview


I'm trying to check if the a user default exists, seen below:

func userAlreadyExist() -> Bool {
    var userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
    
    if userDefaults.objectForKey(kUSERID) {
        return true
    }
    
    return false
}

However, no mater what it will always return true even when the object doesn't exist yet? Is this the right way for checking existence ?

Ios Solutions


Solution 1 - Ios

Astun has a great answer. See below for the Swift 3 version.

func isKeyPresentInUserDefaults(key: String) -> Bool {
    return UserDefaults.standard.object(forKey: key) != nil
}

Solution 2 - Ios

I copy/pasted your code but Xcode 6.1.1 was throwing some errors my way, it ended up looking like this and it works like a charm. Thanks!

func userAlreadyExist(kUsernameKey: String) -> Bool {
    return NSUserDefaults.standardUserDefaults().objectForKey(kUsernameKey) != nil
}

Swift 5:

if UserDefaults.standard.object(forKey: "keyName") != nil {
  //Key exists
}

Solution 3 - Ios

Yes this is right way to check the optional have nil or any value objectForKey method returns AnyObject? which is Implicit optional.

So if userDefaults.objectForKey(kUSERID) have any value than it evaluates to true. if userDefaults.objectForKey(kUSERID) has nil value than it evaluates to false.

From swift programming guide > If Statements and Forced Unwrapping > You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to > true; if it has no value at all, it evaluates to false.

Now there is a bug in simulators than after setting key in userDefaults they always remain set no matter you delete your app.You need to reset simulator.

Reset your Simulator check this method before setting key in userDefaults or remove key userDefaults.removeObjectForKey(kUSERID) from userDefaults and it will return NO.On devices it is resolved in iOS8 beta4.

Solution 4 - Ios

This is essentially the same as suggested in other answers but in a more convenient way (Swift 3+):

extension UserDefaults {
    static func contains(_ key: String) -> Bool {
        return UserDefaults.standard.object(forKey: key) != nil
    }
}

usage: if UserDefaults.contains(kUSERID) { ... }

Solution 5 - Ios

Simple Code to check whether value stored in UserDefault.

let userdefaults = UserDefaults.standard
if let savedValue = userdefaults.string(forKey: "key"){
   print("Here you will get saved value")       
} else {
   print("No value in Userdefault,Either you can save value here or perform other operation")
   userdefaults.set("Here you can save value", forKey: "key")
}

Solution 6 - Ios

Many of the solutions here are valid. Still, I think they solve the wrong problem.

Usually, code like this is used to check if a value is set so another default value can be used:

if isKeyPresentInUserDefaults(key: "username") {
    return UserDefaults.standard.string(forKey: "username")
} else {
    return "No username was set"
}

You shouldn't care if a key is set or not. There is a far more elegant approach for having default values in UserDefaults:

UserDefault.standard.register(defaults: ["username": "No username was set"])

If you run this code at app launch, subsequent calls to UserDefaults.standard.string(forKey: "username") will return the default value of "No username was set" if no value was set for the key yet.

Solution 7 - Ios

for swift 3.2

func userAlreadyExist(kUsernameKey: String) -> Bool {
    return UserDefaults.standard.object(forKey: kUsernameKey) != nil
}

Solution 8 - Ios

public class PreferencesUtils {
    
    private init() {
    
    }
    
    public static func setBoolData(boolValue: Bool, dataName: String) {
        UserDefaults.standard.set(boolValue, forKey: dataName)
    }
    
    public static func getBoolData(dataName: String)-> Bool{
        
        let defaults = UserDefaults.standard
        
        if(defaults.value(forKey: dataName) != nil) {
            return defaults.value(forKey: dataName)! as! Bool
            
        } else {
            return false
        }
    }
    
    public static func saveStringData(data: String, dataName: String){
        let preferences = UserDefaults.standard
        preferences.set(data, forKey: dataName)
        let didSave = preferences.synchronize()
        if !didSave {
            debugPrint("Not saved yet")
        }
    }
    
    public static func getSavedStringData(dataName: String)-> String{
        let defaults = UserDefaults.standard
        if(defaults.value(forKey: dataName) != nil){
            return defaults.value(forKey: dataName) as! String
        } else {
            return ""
        }
    }
    
    public static func saveIntData(data : Int, dataName: String){
        let preferences = UserDefaults.standard
        preferences.set(data, forKey: dataName)
        let didSave = preferences.synchronize()
        if !didSave {
            debugPrint("Not saved yet")
        }
    }
    
    public static func getSavedIntData(dataName: String) -> Int {
        let defaults = UserDefaults.standard
        if(defaults.value(forKey: dataName) != nil){
            return defaults.value(forKey: dataName) as! Int
        }else{
            return 0
        }
    }
    
}

Or you can try this library: Link

Solution 9 - Ios

func keyExists(key: String) -> Bool {
    guard let _ = UserDefaults.standard.object(forKey: key) {
     return false;
    }

   return true;
}

Solution 10 - Ios

override func viewDidLoad() {

super.viewDidLoad()

if UserDefaults.standard.string(forKey: "CHARRY") == "CHARRY"{

 lb.text = "CHARRY"

 im.image = UIImage(named: "CHARRY")

} }

@IBAction func PressedCar(_ sender: UIButton){

 lb.text = "CHARRY"

 im.image = UIImage(named: "CHARRY")

 UserDefaults.standard.set("CAR", forKey: "CHARRY")


}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanView Question on Stackoverflow
Solution 1 - Iosuser7248923View Answer on Stackoverflow
Solution 2 - IosAstunView Answer on Stackoverflow
Solution 3 - IoscodesterView Answer on Stackoverflow
Solution 4 - IosSir CodesalotView Answer on Stackoverflow
Solution 5 - IosSudhi 9135View Answer on Stackoverflow
Solution 6 - IosXavier LowmillerView Answer on Stackoverflow
Solution 7 - IosJohny D GoodView Answer on Stackoverflow
Solution 8 - IosJamil Hasnine TamimView Answer on Stackoverflow
Solution 9 - IosAndrea LeganzaView Answer on Stackoverflow
Solution 10 - IosM Hamayun zebView Answer on Stackoverflow